<!DOCTYPE html>
<html lang="zh-CN">
    <!-- title -->


    

<!-- keywords -->



<head>
    <meta charset="utf-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0, user-scalable=no">
    <meta name="author" content="Binisalegend">
    <meta name="renderer" content="webkit">
    <meta name="copyright" content="Binisalegend">
    
        <meta name="keywords" content="hexo,hexo-theme,hexo-blog">
    
    <meta name="description" content="">
    <meta name="description" content="本文是伯克利CS61A课程的配套学习笔记">
<meta property="og:type" content="article">
<meta property="og:title" content="CS61A学习笔记">
<meta property="og:url" content="https://binisalegend.github.io/2023/11/08/CS61A%E5%AD%A6%E4%B9%A0%E7%AC%94%E8%AE%B0/index.html">
<meta property="og:site_name" content="Binisalegend的博客">
<meta property="og:description" content="本文是伯克利CS61A课程的配套学习笔记">
<meta property="og:locale" content="zh_CN">
<meta property="og:image" content="https://binisalegend.github.io/2023/11/08/CS61A%E5%AD%A6%E4%B9%A0%E7%AC%94%E8%AE%B0/Pasted%20image%2020230708150326.png">
<meta property="og:image" content="https://binisalegend.github.io/2023/11/08/CS61A%E5%AD%A6%E4%B9%A0%E7%AC%94%E8%AE%B0/Pasted%20image%2020230708151420.png">
<meta property="og:image" content="https://binisalegend.github.io/2023/11/08/CS61A%E5%AD%A6%E4%B9%A0%E7%AC%94%E8%AE%B0/Pasted%20image%2020230708151721.png">
<meta property="og:image" content="https://binisalegend.github.io/2023/11/08/CS61A%E5%AD%A6%E4%B9%A0%E7%AC%94%E8%AE%B0/Pasted%20image%2020230708214014.png">
<meta property="og:image" content="https://binisalegend.github.io/2023/11/08/CS61A%E5%AD%A6%E4%B9%A0%E7%AC%94%E8%AE%B0/Pasted%20image%2020230708215032.png">
<meta property="og:image" content="https://binisalegend.github.io/2023/11/08/CS61A%E5%AD%A6%E4%B9%A0%E7%AC%94%E8%AE%B0/Pasted%20image%2020230708220818.png">
<meta property="og:image" content="https://binisalegend.github.io/2023/11/08/CS61A%E5%AD%A6%E4%B9%A0%E7%AC%94%E8%AE%B0/Pasted%20image%2020230708220836.png">
<meta property="og:image" content="https://binisalegend.github.io/2023/11/08/CS61A%E5%AD%A6%E4%B9%A0%E7%AC%94%E8%AE%B0/Pasted%20image%2020230708221101.png">
<meta property="og:image" content="https://binisalegend.github.io/2023/11/08/CS61A%E5%AD%A6%E4%B9%A0%E7%AC%94%E8%AE%B0/Pasted%20image%2020230709005548.png">
<meta property="og:image" content="https://binisalegend.github.io/2023/11/08/CS61A%E5%AD%A6%E4%B9%A0%E7%AC%94%E8%AE%B0/Pasted%20image%2020230709005813.png">
<meta property="og:image" content="https://binisalegend.github.io/2023/11/08/CS61A%E5%AD%A6%E4%B9%A0%E7%AC%94%E8%AE%B0/Pasted%20image%2020230711220439.png">
<meta property="og:image" content="https://binisalegend.github.io/2023/11/08/CS61A%E5%AD%A6%E4%B9%A0%E7%AC%94%E8%AE%B0/Pasted%20image%2020230722005339.png">
<meta property="og:image" content="https://binisalegend.github.io/2023/11/08/CS61A%E5%AD%A6%E4%B9%A0%E7%AC%94%E8%AE%B0/Pasted%20image%2020230808143852.png">
<meta property="og:image" content="https://binisalegend.github.io/2023/11/08/CS61A%E5%AD%A6%E4%B9%A0%E7%AC%94%E8%AE%B0/Pasted%20image%2020230809134011.png">
<meta property="og:image" content="https://binisalegend.github.io/2023/11/08/CS61A%E5%AD%A6%E4%B9%A0%E7%AC%94%E8%AE%B0/Pasted%20image%2020230809140009.png">
<meta property="og:image" content="https://binisalegend.github.io/2023/11/08/CS61A%E5%AD%A6%E4%B9%A0%E7%AC%94%E8%AE%B0/Pasted%20image%2020230809201405.png">
<meta property="article:published_time" content="2023-11-08T02:40:09.000Z">
<meta property="article:modified_time" content="2023-11-08T03:32:44.884Z">
<meta property="article:author" content="Binisalegend">
<meta property="article:tag" content="Python">
<meta name="twitter:card" content="summary">
<meta name="twitter:image" content="https://binisalegend.github.io/2023/11/08/CS61A%E5%AD%A6%E4%B9%A0%E7%AC%94%E8%AE%B0/Pasted%20image%2020230708150326.png">
    <meta http-equiv="Cache-control" content="no-cache">
    <meta http-equiv="X-UA-Compatible" content="IE=edge,chrome=1">
    <link rel="icon" href="/assets/favicon.ico">
    
    <title>CS61A学习笔记 · Binisalegend&#39;s Studio</title>
    <!-- /*! loadCSS. [c]2017 Filament Group, Inc. MIT License */
/* This file is meant as a standalone workflow for
- testing support for link[rel=preload]
- enabling async CSS loading in browsers that do not support rel=preload
- applying rel preload css once loaded, whether supported or not.
*/ -->
<script>
    (function (w) {
        'use strict'
        // rel=preload support test
        if (!w.loadCSS) {
            w.loadCSS = function () {}
        }
        // define on the loadCSS obj
        var rp = (loadCSS.relpreload = {})
        // rel=preload feature support test
        // runs once and returns a function for compat purposes
        rp.support = (function () {
            var ret
            try {
                ret = w.document.createElement('link').relList.supports('preload')
            } catch (e) {
                ret = false
            }
            return function () {
                return ret
            }
        })()

        // if preload isn't supported, get an asynchronous load by using a non-matching media attribute
        // then change that media back to its intended value on load
        rp.bindMediaToggle = function (link) {
            // remember existing media attr for ultimate state, or default to 'all'
            var finalMedia = link.media || 'all'

            function enableStylesheet() {
                link.media = finalMedia
            }

            // bind load handlers to enable media
            if (link.addEventListener) {
                link.addEventListener('load', enableStylesheet)
            } else if (link.attachEvent) {
                link.attachEvent('onload', enableStylesheet)
            }

            // Set rel and non-applicable media type to start an async request
            // note: timeout allows this to happen async to let rendering continue in IE
            setTimeout(function () {
                link.rel = 'stylesheet'
                link.media = 'only x'
            })
            // also enable media after 3 seconds,
            // which will catch very old browsers (android 2.x, old firefox) that don't support onload on link
            setTimeout(enableStylesheet, 3000)
        }

        // loop through link elements in DOM
        rp.poly = function () {
            // double check this to prevent external calls from running
            if (rp.support()) {
                return
            }
            var links = w.document.getElementsByTagName('link')
            for (var i = 0; i < links.length; i++) {
                var link = links[i]
                // qualify links to those with rel=preload and as=style attrs
                if (
                    link.rel === 'preload' &&
                    link.getAttribute('as') === 'style' &&
                    !link.getAttribute('data-loadcss')
                ) {
                    // prevent rerunning on link
                    link.setAttribute('data-loadcss', true)
                    // bind listeners to toggle media back
                    rp.bindMediaToggle(link)
                }
            }
        }

        // if unsupported, run the polyfill
        if (!rp.support()) {
            // run once at least
            rp.poly()

            // rerun poly on an interval until onload
            var run = w.setInterval(rp.poly, 500)
            if (w.addEventListener) {
                w.addEventListener('load', function () {
                    rp.poly()
                    w.clearInterval(run)
                })
            } else if (w.attachEvent) {
                w.attachEvent('onload', function () {
                    rp.poly()
                    w.clearInterval(run)
                })
            }
        }

        // commonjs
        if (typeof exports !== 'undefined') {
            exports.loadCSS = loadCSS
        } else {
            w.loadCSS = loadCSS
        }
    })(typeof global !== 'undefined' ? global : this)
</script>

    <style type="text/css">
    @font-face {
        font-family: 'Oswald-Regular';
        src: url("/font/Oswald-Regular.ttf");
    }

    body {
        margin: 0;
    }

    header,
    footer,
    .back-top,
    .sidebar,
    .container,
    .site-intro-meta,
    .toc-wrapper {
        display: none;
    }

    .site-intro {
        position: relative;
        z-index: 3;
        width: 100%;
        /* height: 50vh; */
        overflow: hidden;
    }

    .site-intro-placeholder {
        position: absolute;
        z-index: -2;
        top: 0;
        left: 0;
        width: calc(100% + 300px);
        height: 100%;
        background: repeating-linear-gradient(-45deg, #444 0, #444 80px, #333 80px, #333 160px);
        background-position: center center;
        transform: translate3d(-226px, 0, 0);
        animation: gradient-move 2.5s ease-out 0s infinite;
    }

    @keyframes gradient-move {
        0% {
            transform: translate3d(-226px, 0, 0);
        }
        100% {
            transform: translate3d(0, 0, 0);
        }
    }
</style>

    <link rel="preload" href="/css/style.css?v=20211217" as="style" onload="this.onload=null;this.rel='stylesheet'">
    <link rel="preload" href="/css/dark.css?v=20211217" as="style">
    <link rel="stylesheet" href="/css/dark.css">
    <link rel="stylesheet" href="/css/mobile.css?v=20211217" media="(max-width: 960px)">
    <link rel="preload" href="https://cdn.jsdelivr.net/npm/@fancyapps/fancybox@3.5.7/dist/jquery.fancybox.min.css" as="style" onload="this.onload=null;this.rel='stylesheet'">
    <link rel="preload" href="https://cdn.jsdelivr.net/npm/jquery@3.6.0/dist/jquery.min.js" as="script">
    <link rel="preload" href="/scripts/main.js?v=20211217" as="script">
    <link rel="preload" href="/scripts/dark.js?v=20211217" as="script">
    <link rel="preload" href="/font/Oswald-Regular.ttf" as="font" crossorigin>
    <link rel="preload" href="https://at.alicdn.com/t/font_327081_1dta1rlogw17zaor.woff" as="font" crossorigin>
    <!-- algolia -->
    
    <!-- 百度统计  -->
    
    <!-- 谷歌统计  -->
    
<!-- hexo injector head_end start -->
<link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/katex@0.12.0/dist/katex.min.css">

<link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/hexo-math@4.0.0/dist/style.css">
<!-- hexo injector head_end end --><meta name="generator" content="Hexo 6.3.0"></head>

    <script src="https://cdn.jsdelivr.net/npm/jquery@3.6.0/dist/jquery.min.js"></script>
    <script type="text/javascript">
        if (typeof window.$ == undefined) {
            console.warn('jquery load from jsdelivr failed, will load local script')
            document.write('<script src="/lib/jquery.min.js" />')
        }
    </script>
    
        <body class="post-body">
    
        <!-- header -->
        <header class="header header-mobile">
    <!-- top read progress line -->
    <div class="header-element">
        <div class="read-progress"></div>
    </div>
    <!-- sidebar menu button -->
    <div class="header-element">
        
            <div class="header-sidebar-menu">
        
            
                <div style="padding-left: 1px;">&#xe775;</div>
            
        </div>
    </div>
    <!-- header actions -->
    <div class="header-actions">
        <!-- theme mode switch button -->
        <span class="header-theme-btn header-element">
            <i class="fas fa-adjust"></i>
        </span>
        <!-- back to home page text -->
        <span class="home-link header-element">
            <a href=/>锅中冰's Studio.</a>
        </span>
    </div>
    <!-- toggle banner for post layout -->
    
        
            <div class="banner">
        
            <div class="blog-title header-element">
                <a href="/">锅中冰&#39;s Studio.</a>
            </div>
            <div class="post-title header-element">
                <a href="#" class="post-name">CS61A学习笔记</a>
            </div>
        </div>
    
</header>

        <!-- fixed footer -->
        <footer class="footer-fixed">
    <!-- back to top button -->
    <div class="footer-fixed-element">
        
            <div class="back-top back-top-hidden">
        
        
            <div>&#xe639;</div>
        
        </div>
    </div>
</footer>

        <!-- wrapper -->
        <div class="wrapper">
            <div class="site-intro" style="







    height:50vh;

">
    
    <!-- 主页  -->
    
        
    <!-- 404页  -->
    
    <div class="site-intro-placeholder"></div>
    <div class="site-intro-img" style="background-image: url(https://source.unsplash.com/2560x800/?programming)"></div>
    <div class="site-intro-meta">
        <!-- 标题  -->
        <h1 class="intro-title">
            <!-- 主页  -->
            
                CS61A学习笔记
            <!-- 404 -->
            
        </h1>
        <!-- 副标题 -->
        <p class="intro-subtitle">
            <!-- 主页副标题  -->
            
                
            <!-- 404 -->
            
        </p>
        <!-- 文章页 meta -->
        
            <div class="post-intros">
                <!-- 文章页标签  -->
                
                    <div class= post-intro-tags >
    
    
        <a class="post-tag" href="javascript:void(0);" data-tags="Python">Python</a>
    
</div>

                
                <!-- 文章字数统计 -->
                
                    <div class="post-intro-read">
                        <span>字数统计: <span class="post-count word-count">14.6k</span>阅读时长: <span class="post-count reading-time">67 min</span></span>
                    </div>
                
                <div class="post-intro-meta">
                    <!-- 撰写日期 -->
                    <span class="iconfont-archer post-intro-calander">&#xe676;</span>
                    <span class="post-intro-time">2023/11/08</span>
                    <!-- busuanzi -->
                    
                        <span id="busuanzi_container_page_pv" class="busuanzi-pv">
                            <span class="iconfont-archer post-intro-busuanzi">&#xe602;</span>
                            <span id="busuanzi_value_page_pv"></span>
                        </span>
                    
                    <!-- 文章分享 -->
                    <span class="share-wrapper">
                        <span class="iconfont-archer share-icon">&#xe71d;</span>
                        <span class="share-text">Share</span>
                        <ul class="share-list">
                            <li class="iconfont-archer share-qr" data-type="qr">&#xe75b;
                                <div class="share-qrcode"></div>
                            </li>
                            <li class="iconfont-archer" data-type="weibo">&#xe619;</li>
                            <li class="iconfont-archer" data-type="qzone">&#xe62e;</li>
                            <li class="iconfont-archer" data-type="twitter">&#xe634;</li>
                            <li class="iconfont-archer" data-type="facebook">&#xe67a;</li>
                        </ul>
                    </span>
                </div>
            </div>
        
    </div>
</div>

            <script>
  // get user agent
  function getBrowserVersions() {
    var u = window.navigator.userAgent
    return {
      userAgent: u,
      trident: u.indexOf('Trident') > -1, //IE内核
      presto: u.indexOf('Presto') > -1, //opera内核
      webKit: u.indexOf('AppleWebKit') > -1, //苹果、谷歌内核
      gecko: u.indexOf('Gecko') > -1 && u.indexOf('KHTML') == -1, //火狐内核
      mobile: !!u.match(/AppleWebKit.*Mobile.*/), //是否为移动终端
      ios: !!u.match(/\(i[^;]+;( U;)? CPU.+Mac OS X/), //ios终端
      android: u.indexOf('Android') > -1 || u.indexOf('Linux') > -1, //android终端或者uc浏览器
      iPhone: u.indexOf('iPhone') > -1 || u.indexOf('Mac') > -1, //是否为iPhone或者安卓QQ浏览器
      iPad: u.indexOf('iPad') > -1, //是否为iPad
      webApp: u.indexOf('Safari') == -1, //是否为web应用程序，没有头部与底部
      weixin: u.indexOf('MicroMessenger') == -1, //是否为微信浏览器
      uc: u.indexOf('UCBrowser') > -1, //是否为android下的UC浏览器
    }
  }
  var browser = {
    versions: getBrowserVersions(),
  }
  console.log('userAgent: ' + browser.versions.userAgent)

  // callback
  function fontLoaded() {
    console.log('font loaded')
    if (document.getElementsByClassName('site-intro-meta')) {
      document
        .getElementsByClassName('intro-title')[0]
        .classList.add('intro-fade-in')
      document
        .getElementsByClassName('intro-subtitle')[0]
        .classList.add('intro-fade-in')
      var postIntros = document.getElementsByClassName('post-intros')[0]
      if (postIntros) {
        postIntros.classList.add('post-fade-in')
      }
    }
  }

  // UC不支持跨域，所以直接显示
  function asyncCb() {
    if (browser.versions.uc) {
      console.log('UCBrowser')
      fontLoaded()
    } else {
      WebFont.load({
        custom: {
          families: ['Oswald-Regular'],
        },
        loading: function () {
          // 所有字体开始加载
          // console.log('font loading');
        },
        active: function () {
          // 所有字体已渲染
          fontLoaded()
        },
        inactive: function () {
          // 字体预加载失败，无效字体或浏览器不支持加载
          console.log('inactive: timeout')
          fontLoaded()
        },
        timeout: 5000, // Set the timeout to two seconds
      })
    }
  }

  function asyncErr() {
    console.warn('script load from CDN failed, will load local script')
  }

  // load webfont-loader async, and add callback function
  function async(u, cb, err) {
    var d = document,
      t = 'script',
      o = d.createElement(t),
      s = d.getElementsByTagName(t)[0]
    o.src = u
    if (cb) {
      o.addEventListener(
        'load',
        function (e) {
          cb(null, e)
        },
        false
      )
    }
    if (err) {
      o.addEventListener(
        'error',
        function (e) {
          err(null, e)
        },
        false
      )
    }
    s.parentNode.insertBefore(o, s)
  }

  var asyncLoadWithFallBack = function (arr, success, reject) {
    var currReject = function () {
      reject()
      arr.shift()
      if (arr.length) async(arr[0], success, currReject)
    }

    async(arr[0], success, currReject)
  }

  asyncLoadWithFallBack(
    [
      'https://cdn.jsdelivr.net/npm/webfontloader@1.6.28/webfontloader.min.js',
      'https://cdn.bootcss.com/webfont/1.6.28/webfontloader.js',
      "/lib/webfontloader.min.js",
    ],
    asyncCb,
    asyncErr
  )
</script>

            <img class="loading" src="/assets/loading.svg" style="display: block; margin: 6rem auto 0 auto; width: 6rem; height: 6rem;" />
            <div class="container container-unloaded">
                <main class="main post-page">
    <article class="article-entry">
        <p>本文是伯克利CS61A课程的配套学习笔记</p>
<span id="more"></span>

<h1 id="Lecture-3-Control（函数控制）"><a href="#Lecture-3-Control（函数控制）" class="headerlink" title="Lecture 3 : Control（函数控制）"></a>Lecture 3 : Control（函数控制）</h1><h2 id="HW01-Variables-Functions-Control"><a href="#HW01-Variables-Functions-Control" class="headerlink" title="HW01 : Variables &amp; Functions, Control"></a><em>HW01 : Variables &amp; Functions, Control</em></h2><ul>
<li>可以给函数重新命名，或者理解为将一个函数的功能赋给另一个函数<figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">from</span> operator <span class="keyword">import</span> add, sub  </span><br><span class="line">  </span><br><span class="line"><span class="keyword">def</span> <span class="title function_">a_plus_abs_b</span>(<span class="params">a, b</span>):  </span><br><span class="line">    <span class="string">&quot;&quot;&quot;Return a+abs(b), but without calling abs.&quot;&quot;&quot;</span></span><br><span class="line">    <span class="keyword">if</span> b &gt;= <span class="number">0</span>:  </span><br><span class="line">        h = add  </span><br><span class="line">    <span class="keyword">else</span>:  </span><br><span class="line">        h = sub  </span><br><span class="line">    <span class="keyword">return</span> h(a, b)</span><br></pre></td></tr></table></figure></li>
<li><input disabled type="checkbox"> 这个理解不了一点，不知道那个with_if_statement干啥用的<figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br><span class="line">32</span><br><span class="line">33</span><br><span class="line">34</span><br><span class="line">35</span><br><span class="line">36</span><br><span class="line">37</span><br><span class="line">38</span><br><span class="line">39</span><br><span class="line">40</span><br><span class="line">41</span><br><span class="line">42</span><br><span class="line">43</span><br><span class="line">44</span><br><span class="line">45</span><br><span class="line">46</span><br><span class="line">47</span><br><span class="line">48</span><br><span class="line">49</span><br><span class="line">50</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">def</span> <span class="title function_">if_function</span>(<span class="params">condition, true_result, false_result</span>):  </span><br><span class="line">    <span class="string">&quot;&quot;&quot;Return true_result if condition is a true value, and  </span></span><br><span class="line"><span class="string">    false_result otherwise. </span></span><br><span class="line"><span class="string">    </span></span><br><span class="line"><span class="string">    &gt;&gt;&gt; if_function(True, 2, 3)</span></span><br><span class="line"><span class="string">    2</span></span><br><span class="line"><span class="string">    &gt;&gt;&gt; if_function(False, 2, 3)</span></span><br><span class="line"><span class="string">	3</span></span><br><span class="line"><span class="string">	&gt;&gt;&gt; if_function(3==2, 3+2, 3-2)</span></span><br><span class="line"><span class="string">	1</span></span><br><span class="line"><span class="string">	&gt;&gt;&gt; if_function(3&gt;2, 3+2, 3-2)    </span></span><br><span class="line"><span class="string">	5</span></span><br><span class="line"><span class="string">	&quot;&quot;&quot;</span>    </span><br><span class="line">	<span class="keyword">if</span> condition:  </span><br><span class="line">        <span class="keyword">return</span> true_result  </span><br><span class="line">    <span class="keyword">else</span>:  </span><br><span class="line">        <span class="keyword">return</span> false_result  </span><br><span class="line">  </span><br><span class="line">  </span><br><span class="line"><span class="keyword">def</span> <span class="title function_">with_if_statement</span>():  </span><br><span class="line">    <span class="string">&quot;&quot;&quot;  </span></span><br><span class="line"><span class="string">    &gt;&gt;&gt; result = with_if_statement()    </span></span><br><span class="line"><span class="string">    47</span></span><br><span class="line"><span class="string">    &gt;&gt;&gt; print(result) </span></span><br><span class="line"><span class="string">    None</span></span><br><span class="line"><span class="string">    &quot;&quot;&quot;</span></span><br><span class="line">    <span class="keyword">if</span> cond():  </span><br><span class="line">        <span class="keyword">return</span> true_func()  </span><br><span class="line">    <span class="keyword">else</span>:  </span><br><span class="line">        <span class="keyword">return</span> false_func()  </span><br><span class="line">  </span><br><span class="line"><span class="keyword">def</span> <span class="title function_">with_if_function</span>():  </span><br><span class="line">    <span class="string">&quot;&quot;&quot;  </span></span><br><span class="line"><span class="string">    &gt;&gt;&gt; result = with_if_function()</span></span><br><span class="line"><span class="string">	42</span></span><br><span class="line"><span class="string">	47</span></span><br><span class="line"><span class="string">	&gt;&gt;&gt; print(result)    </span></span><br><span class="line"><span class="string">	None    </span></span><br><span class="line"><span class="string">	&quot;&quot;&quot;</span>    </span><br><span class="line">	<span class="keyword">return</span> if_function(cond(), true_func(), false_func())  </span><br><span class="line">  </span><br><span class="line"><span class="keyword">def</span> <span class="title function_">cond</span>():  </span><br><span class="line">    <span class="string">&quot;*** YOUR CODE HERE ***&quot;</span>  </span><br><span class="line">    <span class="keyword">return</span> <span class="literal">False</span>  </span><br><span class="line"><span class="keyword">def</span> <span class="title function_">true_func</span>():  </span><br><span class="line">    <span class="string">&quot;*** YOUR CODE HERE ***&quot;</span>  </span><br><span class="line">    <span class="built_in">print</span>(<span class="number">42</span>)  </span><br><span class="line"><span class="keyword">def</span> <span class="title function_">false_func</span>():  </span><br><span class="line">    <span class="string">&quot;*** YOUR CODE HERE ***&quot;</span>  </span><br><span class="line">    <span class="built_in">print</span>(<span class="number">47</span>)</span><br></pre></td></tr></table></figure></li>
<li>def定义一个函数，如果给这个函数调用赋予变量名，系统只会打印定义该变量过程中的print，而不会返回return值，需要再次调用变量才会打印return；而如果不给函数调用赋予变量名，则视为直接计算函数值也会打印return值<figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">def</span> <span class="title function_">hailstone</span>(<span class="params">x</span>):  </span><br><span class="line">    <span class="built_in">print</span>(x)  </span><br><span class="line">    cnt = <span class="number">1</span>  </span><br><span class="line">    <span class="keyword">while</span> x != <span class="number">1</span>:  </span><br><span class="line">        cnt += <span class="number">1</span>  </span><br><span class="line">        <span class="keyword">if</span> x % <span class="number">2</span> == <span class="number">0</span>:  </span><br><span class="line">            x = x // <span class="number">2</span>  </span><br><span class="line">            <span class="built_in">print</span>(x)  </span><br><span class="line">        <span class="keyword">else</span>:  </span><br><span class="line">            x = x * <span class="number">3</span> + <span class="number">1</span>  </span><br><span class="line">            <span class="built_in">print</span>(x)  </span><br><span class="line">    <span class="keyword">return</span> cnt</span><br></pre></td></tr></table></figure>
![[Pasted image 20230710114432.png]]</li>
</ul>
<h2 id="Lab01-Variables-Functions-Control"><a href="#Lab01-Variables-Functions-Control" class="headerlink" title="Lab01: Variables &amp; Functions, Control"></a><em>Lab01: Variables &amp; Functions, Control</em></h2><ul>
<li>一些OK常用语句：<ol>
<li>在输出行前打“DEBUG:”可以避免误识别print内容</li>
<li><code>python3 ok -q sum_digits -i </code>和  <code>python3 ok -q sum_digits -trace</code>没弄清楚啥意思，再摸索摸索（bushi</li>
<li><code>python3 -q doctest &lt;文件名&gt;</code> 可以运行程序中的测试</li>
</ol>
</li>
<li><code>for i in range n:</code> 语句表示从i到n-1，意思是包含i，但不包含n。字面意思，区分一下</li>
</ul>
<h1 id="Lecture-4-Higher-Order-Functions（高阶函数）"><a href="#Lecture-4-Higher-Order-Functions（高阶函数）" class="headerlink" title="Lecture 4:Higher-Order Functions（高阶函数）"></a>Lecture 4:Higher-Order Functions（高阶函数）</h1><h2 id="function-example-sound"><a href="#function-example-sound" class="headerlink" title="function example: sound"></a><em>function example: sound</em></h2><ul>
<li>利用python进行三角波的形成和输出、整合，验证高级函数实用性<figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br><span class="line">32</span><br><span class="line">33</span><br><span class="line">34</span><br><span class="line">35</span><br><span class="line">36</span><br><span class="line">37</span><br><span class="line">38</span><br><span class="line">39</span><br><span class="line">40</span><br><span class="line">41</span><br><span class="line">42</span><br><span class="line">43</span><br><span class="line">44</span><br><span class="line">45</span><br><span class="line">46</span><br><span class="line">47</span><br><span class="line">48</span><br><span class="line">49</span><br><span class="line">50</span><br><span class="line">51</span><br><span class="line">52</span><br><span class="line">53</span><br><span class="line">54</span><br><span class="line">55</span><br><span class="line">56</span><br><span class="line">57</span><br><span class="line">58</span><br><span class="line">59</span><br><span class="line">60</span><br><span class="line">61</span><br><span class="line">62</span><br><span class="line">63</span><br><span class="line">64</span><br><span class="line">65</span><br><span class="line">66</span><br><span class="line">67</span><br><span class="line">68</span><br><span class="line">69</span><br><span class="line">70</span><br><span class="line">71</span><br><span class="line">72</span><br><span class="line">73</span><br><span class="line">74</span><br><span class="line">75</span><br><span class="line">76</span><br><span class="line">77</span><br><span class="line">78</span><br><span class="line">79</span><br><span class="line">80</span><br><span class="line">81</span><br><span class="line">82</span><br><span class="line">83</span><br><span class="line">84</span><br><span class="line">85</span><br><span class="line">86</span><br><span class="line">87</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">from</span> wave <span class="keyword">import</span> <span class="built_in">open</span>  </span><br><span class="line"><span class="keyword">from</span> struct <span class="keyword">import</span> Struct  </span><br><span class="line"><span class="keyword">from</span> math <span class="keyword">import</span> floor  </span><br><span class="line">  </span><br><span class="line">frame_rate = <span class="number">11025</span>  </span><br><span class="line">  </span><br><span class="line"><span class="keyword">def</span> <span class="title function_">encode</span>(<span class="params">x</span>):  </span><br><span class="line">    <span class="string">&quot;&quot;&quot;Encode float x between -1 and 1 as two bytes.  </span></span><br><span class="line"><span class="string">	(See https://docs.python.org/3/library/struct.html)&quot;&quot;&quot;</span></span><br><span class="line">	i = <span class="built_in">int</span>(<span class="number">16384</span> * x)  </span><br><span class="line">    <span class="keyword">return</span> Struct(<span class="string">&#x27;h&#x27;</span>).pack(i)  </span><br><span class="line">  </span><br><span class="line"><span class="keyword">def</span> <span class="title function_">play</span>(<span class="params">sampler, name=<span class="string">&#x27;song.wav&#x27;</span>, seconds=<span class="number">2</span></span>):  </span><br><span class="line">    <span class="string">&quot;&quot;&quot;Write the output of a sampler function as a wav file.  </span></span><br><span class="line"><span class="string">    (See https://docs.python.org/3/library/wave.html) &quot;&quot;&quot;</span> </span><br><span class="line">	out = <span class="built_in">open</span>(name, <span class="string">&#x27;wb&#x27;</span>)  </span><br><span class="line">    out.setnchannels(<span class="number">1</span>)  </span><br><span class="line">    out.setsampwidth(<span class="number">2</span>)  </span><br><span class="line">    out.setframerate(frame_rate)  </span><br><span class="line">    t = <span class="number">0</span>  </span><br><span class="line">    <span class="keyword">while</span> t &lt; seconds * frame_rate:  </span><br><span class="line">        sample = sampler(t)  </span><br><span class="line">        out.writeframes(encode(sample))  </span><br><span class="line">        t = t + <span class="number">1</span>  </span><br><span class="line">    out.close()  </span><br><span class="line">  </span><br><span class="line"><span class="keyword">def</span> <span class="title function_">tri</span>(<span class="params">frequency, amplitude=<span class="number">0.3</span></span>):  </span><br><span class="line">    <span class="string">&quot;&quot;&quot;A continuous triangle wave.&quot;&quot;&quot;</span>  </span><br><span class="line">    period = frame_rate // frequency  </span><br><span class="line">    <span class="keyword">def</span> <span class="title function_">sampler</span>(<span class="params">t</span>):  </span><br><span class="line">        saw_wave = t / period - floor(t / period + <span class="number">0.5</span>)  </span><br><span class="line">        tri_wave = <span class="number">2</span> * <span class="built_in">abs</span>(<span class="number">2</span> * saw_wave) - <span class="number">1</span>  </span><br><span class="line">        <span class="keyword">return</span> amplitude * tri_wave  </span><br><span class="line">    <span class="keyword">return</span> sampler  </span><br><span class="line">  </span><br><span class="line">c_freq, e_freq, g_freq = <span class="number">261.63</span>, <span class="number">329.63</span>, <span class="number">392.00</span>  </span><br><span class="line">  </span><br><span class="line"><span class="keyword">def</span> <span class="title function_">both</span>(<span class="params">f,g</span>):  </span><br><span class="line">    <span class="keyword">return</span> <span class="keyword">lambda</span> t: f(t) + g(t)  </span><br><span class="line">  </span><br><span class="line"><span class="keyword">def</span> <span class="title function_">note</span>(<span class="params">f,start,end,fade=<span class="number">0.1</span></span>):  </span><br><span class="line">    <span class="keyword">def</span> <span class="title function_">sampler</span>(<span class="params">t</span>):  </span><br><span class="line">        seconds = t / frame_rate  </span><br><span class="line">        <span class="keyword">if</span> seconds &lt; start:  </span><br><span class="line">            <span class="keyword">return</span> <span class="number">0</span>  </span><br><span class="line">        <span class="keyword">elif</span> seconds &gt; end:  </span><br><span class="line">            <span class="keyword">return</span> <span class="number">0</span>  </span><br><span class="line">        <span class="keyword">elif</span> seconds &lt; start + fade:  </span><br><span class="line">            <span class="keyword">return</span> (seconds - start) / fade * f(t)  </span><br><span class="line">        <span class="keyword">elif</span> seconds &gt; end - fade:  </span><br><span class="line">            <span class="keyword">return</span> (end - seconds) / fade * f(t)  </span><br><span class="line">        <span class="keyword">else</span>:  </span><br><span class="line">            <span class="keyword">return</span> f(t)  </span><br><span class="line">    <span class="keyword">return</span> sampler  </span><br><span class="line"></span><br><span class="line"><span class="keyword">def</span> <span class="title function_">mario_at</span>(<span class="params">octave</span>):  </span><br><span class="line">    c = tri(octave * c_freq)  </span><br><span class="line">    e = tri(octave * e_freq)  </span><br><span class="line">    g = tri(octave * g_freq)  </span><br><span class="line">    low_g = tri(octave * g_freq / <span class="number">2</span>)  </span><br><span class="line">    <span class="keyword">return</span> mario(c, e, g, low_g)  </span><br><span class="line">    </span><br><span class="line"><span class="comment"># c,e = tri(c_freq),tri(e_freq)  </span></span><br><span class="line"><span class="comment"># g,low_g = tri(g_freq),tri(g_freq/2)  </span></span><br><span class="line">  </span><br><span class="line"><span class="keyword">def</span> <span class="title function_">mario</span>(<span class="params">c, e, g, low_g</span>):  </span><br><span class="line">    z = <span class="number">0</span>  </span><br><span class="line">    song = note(e, z, z + <span class="number">1</span>/<span class="number">8</span>)  </span><br><span class="line">    z += <span class="number">1</span>/<span class="number">8</span>  </span><br><span class="line">    song = both(song, note(e, z, z + <span class="number">1</span>/<span class="number">8</span>))  </span><br><span class="line">    z += <span class="number">1</span>/<span class="number">4</span>  </span><br><span class="line">    song = both(song, note(e, z, z + <span class="number">1</span>/<span class="number">8</span>))  </span><br><span class="line">    z += <span class="number">1</span>/<span class="number">4</span>  </span><br><span class="line">    song = both(song, note(c, z, z + <span class="number">1</span>/<span class="number">8</span>))  </span><br><span class="line">    z += <span class="number">1</span>/<span class="number">8</span>  </span><br><span class="line">    song = both(song, note(e, z, z + <span class="number">1</span>/<span class="number">8</span>))  </span><br><span class="line">    z += <span class="number">1</span>/<span class="number">4</span>  </span><br><span class="line">    song = both(song, note(g, z, z + <span class="number">1</span>/<span class="number">4</span>))  </span><br><span class="line">    z += <span class="number">1</span>/<span class="number">2</span>  </span><br><span class="line">    song = both(song, note(low_g, z, z + <span class="number">1</span>/<span class="number">4</span>))  </span><br><span class="line">    <span class="keyword">return</span> song  </span><br><span class="line">  </span><br><span class="line"><span class="comment"># play(both(note(c,0,1/4),note(e,1/2,1)))  </span></span><br><span class="line">play(both(mario_at(<span class="number">1</span>),mario_at(<span class="number">1</span>/<span class="number">2</span>)))  </span><br><span class="line">  </span><br><span class="line">  </span><br><span class="line"><span class="comment"># play(both(mario_at(1), mario_at(1/2)))</span></span><br></pre></td></tr></table></figure></li>
</ul>
<h2 id="Function-Composition"><a href="#Function-Composition" class="headerlink" title="Function Composition"></a><em>Function Composition</em></h2><figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">def</span> <span class="title function_">make_adder</span>(<span class="params">n</span>):  </span><br><span class="line">    <span class="keyword">def</span> <span class="title function_">adder</span>(<span class="params">k</span>):  </span><br><span class="line">        <span class="keyword">return</span> k + n  </span><br><span class="line">    <span class="keyword">return</span> adder  </span><br><span class="line">  </span><br><span class="line"><span class="keyword">def</span> <span class="title function_">square</span>(<span class="params">x</span>):  </span><br><span class="line">    <span class="keyword">return</span> x * x  </span><br><span class="line">  </span><br><span class="line"><span class="keyword">def</span> <span class="title function_">triple</span>(<span class="params">x</span>):  </span><br><span class="line">    <span class="keyword">return</span> <span class="number">3</span> * x  </span><br><span class="line">  </span><br><span class="line"><span class="keyword">def</span> <span class="title function_">compose1</span>(<span class="params">f,g</span>):  </span><br><span class="line">    <span class="keyword">def</span> <span class="title function_">h</span>(<span class="params">x</span>):  </span><br><span class="line">        <span class="keyword">return</span> f(g(x))  </span><br><span class="line">    <span class="keyword">return</span> h</span><br></pre></td></tr></table></figure>
<h2 id="Function-Currying"><a href="#Function-Currying" class="headerlink" title="Function Currying"></a><em>Function Currying</em></h2><p>[[#^2f1599]]  [[#^ecfc38]]</p>
<ul>
<li>柯里化是一种将接受多个参数的函数转换为接受单个参数的函数序列的技术。<figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment">#应用def函数进行currying</span></span><br><span class="line"><span class="keyword">def</span> <span class="title function_">curry2</span>(<span class="params">f</span>):  </span><br><span class="line">    <span class="keyword">def</span> <span class="title function_">g</span>(<span class="params">x</span>):  </span><br><span class="line">        <span class="keyword">def</span> <span class="title function_">h</span>(<span class="params">y</span>):  </span><br><span class="line">            <span class="keyword">return</span> f(x,y)  </span><br><span class="line">        <span class="keyword">return</span> h  </span><br><span class="line">    <span class="keyword">return</span> g</span><br></pre></td></tr></table></figure>
<figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment">#应用lambda函数进行currying</span></span><br><span class="line"><span class="keyword">def</span> <span class="title function_">curry1</span>(<span class="params">f</span>):</span><br><span class="line">	<span class="keyword">return</span> <span class="keyword">lambda</span> x : <span class="keyword">lambda</span> y : f(x,y)</span><br></pre></td></tr></table></figure></li>
</ul>
<h2 id="HW02-Higher-Order-Functions"><a href="#HW02-Higher-Order-Functions" class="headerlink" title="HW02 : Higher-Order Functions"></a><em>HW02 : Higher-Order Functions</em></h2><ul>
<li>base和term()应用combiner算法进行计算时受到计算顺序的影响，不能任意调换顺序</li>
<li>！记得考虑特殊情况<figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">def</span> <span class="title function_">accumulate</span>(<span class="params">combiner, base, n, term</span>):  </span><br><span class="line">    <span class="string">&quot;&quot;&quot;Return the result of combining the first n terms in a sequence and base. The terms to be combined are term(1), term(2), ..., term(n).combiner is a two-argument commutative function.</span></span><br><span class="line"><span class="string">      </span></span><br><span class="line"><span class="string">    &gt;&gt;&gt; accumulate(add, 0, 5, identity)  # 0 + 1 + 2 + 3 + 4 + 5</span></span><br><span class="line"><span class="string">	15    </span></span><br><span class="line"><span class="string">	&gt;&gt;&gt; accumulate(add, 11, 5, identity) # 11 + 1 + 2 + 3 + 4 + 5</span></span><br><span class="line"><span class="string">	26    </span></span><br><span class="line"><span class="string">	&gt;&gt;&gt; accumulate(add, 11, 0, identity) # 11</span></span><br><span class="line"><span class="string">	11    </span></span><br><span class="line"><span class="string">	&gt;&gt;&gt; accumulate(add, 11, 3, square)   # 11 + 1^2 + 2^2 + 3^2</span></span><br><span class="line"><span class="string">	25    </span></span><br><span class="line"><span class="string">	&gt;&gt;&gt; accumulate(mul, 2, 3, square)    # 2 * 1^2 * 2^2 * 3^2</span></span><br><span class="line"><span class="string">	72    </span></span><br><span class="line"><span class="string">	&gt;&gt;&gt; accumulate(lambda x, y: x + y + 1, 2, 3, square)</span></span><br><span class="line"><span class="string">	19    </span></span><br><span class="line"><span class="string">	&gt;&gt;&gt; accumulate(lambda x, y: 2 * (x + y), 2, 3, square)</span></span><br><span class="line"><span class="string">	58    </span></span><br><span class="line"><span class="string">	&gt;&gt;&gt; accumulate(lambda x, y: (x + y) % 17, 19, 20, square)</span></span><br><span class="line"><span class="string">	16    </span></span><br><span class="line"><span class="string">	&quot;&quot;&quot;</span>    </span><br><span class="line">	<span class="string">&quot;*** YOUR CODE HERE ***&quot;</span>  </span><br><span class="line">    <span class="keyword">if</span> n != <span class="number">0</span>:  </span><br><span class="line">        x, loc = <span class="number">2</span>, combiner(base,term(<span class="number">1</span>))  </span><br><span class="line">        <span class="keyword">while</span> x &lt;= n:  </span><br><span class="line">            loc = combiner(loc, term(x))  </span><br><span class="line">            x += <span class="number">1</span>  </span><br><span class="line">        <span class="built_in">print</span>(loc)  </span><br><span class="line">    <span class="keyword">else</span>:  </span><br><span class="line">        <span class="built_in">print</span>(base)</span><br></pre></td></tr></table></figure></li>
<li><input disabled type="checkbox"> 应用accumulate函数用print函数会多打印一个None，用return就没问题<figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">def</span> <span class="title function_">summation_using_accumulate</span>(<span class="params">n, term</span>):  </span><br><span class="line">    y = accumulate(add,<span class="number">0</span>,n,term)  </span><br><span class="line">    <span class="keyword">return</span> y</span><br><span class="line">	<span class="string">&quot;&quot;&quot;print(y)&quot;&quot;&quot;</span></span><br></pre></td></tr></table></figure></li>
<li>sub是减，mul是乘…</li>
<li>返回值可以是函数，在compose1函数中的f(x)调用可以不指明</li>
<li>for循环中可以自动赋给未定义变量值为0，while循环不行<figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">def</span> <span class="title function_">compose1</span>(<span class="params">func1, func2</span>):  </span><br><span class="line">    <span class="string">&quot;&quot;&quot;Return a function f, such that f(x) = func1(func2(x)).&quot;&quot;&quot;</span>  </span><br><span class="line">    <span class="keyword">def</span> <span class="title function_">f</span>(<span class="params">x</span>):  </span><br><span class="line">        <span class="keyword">return</span> func1(func2(x))  </span><br><span class="line">    <span class="keyword">return</span> f  </span><br><span class="line">  </span><br><span class="line"><span class="keyword">def</span> <span class="title function_">make_repeater</span>(<span class="params">func, n</span>):  </span><br><span class="line">    <span class="string">&quot;&quot;&quot;Return the function that computes the nth application of func.  </span></span><br><span class="line"><span class="string">  </span></span><br><span class="line"><span class="string">    &gt;&gt;&gt; add_three = make_repeater(increment, 3)    </span></span><br><span class="line"><span class="string">    &gt;&gt;&gt; add_three(5)    </span></span><br><span class="line"><span class="string">    8    </span></span><br><span class="line"><span class="string">    &gt;&gt;&gt; make_repeater(triple, 5)(1) # 3 * 3 * 3 * 3 * 3 * 1</span></span><br><span class="line"><span class="string">	243    </span></span><br><span class="line"><span class="string">	&gt;&gt;&gt; make_repeater(square, 2)(5) # square(square(5))</span></span><br><span class="line"><span class="string">	625    </span></span><br><span class="line"><span class="string">	&gt;&gt;&gt; make_repeater(square, 4)(5) # square(square(square(square(5))))       152587890625    </span></span><br><span class="line"><span class="string">	&gt;&gt;&gt; make_repeater(square, 0)(5) # Yes, it makes sense to apply the function zero times!</span></span><br><span class="line"><span class="string">	5    </span></span><br><span class="line"><span class="string">	&quot;&quot;&quot;</span>    </span><br><span class="line">	<span class="string">&quot;*** YOUR CODE HERE ***&quot;</span>  </span><br><span class="line">    f = func  </span><br><span class="line">    <span class="keyword">if</span> n == <span class="number">0</span>:  </span><br><span class="line">        <span class="keyword">return</span> identity  </span><br><span class="line">    <span class="keyword">for</span> i <span class="keyword">in</span> <span class="built_in">range</span>(n-<span class="number">1</span>):  </span><br><span class="line">        f = compose1(func, f)  </span><br><span class="line">    <span class="keyword">return</span> f</span><br></pre></td></tr></table></figure></li>
</ul>
<h1 id="Lecture-5-Environment-Diagrams（程序环境示意图）"><a href="#Lecture-5-Environment-Diagrams（程序环境示意图）" class="headerlink" title="Lecture 5:Environment Diagrams（程序环境示意图）"></a>Lecture 5:Environment Diagrams（程序环境示意图）</h1><h2 id="Environments-for-Higher-Order-Functions"><a href="#Environments-for-Higher-Order-Functions" class="headerlink" title="Environments for Higher-Order Functions"></a><em>Environments for Higher-Order Functions</em></h2><figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">def</span> <span class="title function_">apply_twice</span>(<span class="params">f,x</span>):  </span><br><span class="line">    <span class="keyword">return</span> f(f(x))  </span><br><span class="line">  </span><br><span class="line"><span class="keyword">def</span> <span class="title function_">square</span>(<span class="params">x</span>):  </span><br><span class="line">    <span class="keyword">return</span> x * x</span><br></pre></td></tr></table></figure>
<h2 id="Higher-Order-Function-Example-Repeat"><a href="#Higher-Order-Function-Example-Repeat" class="headerlink" title="Higher-Order Function Example:Repeat"></a><em>Higher-Order Function Example:Repeat</em></h2><figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">def</span> <span class="title function_">repeat</span>(<span class="params">f,x</span>):  </span><br><span class="line">    <span class="keyword">while</span> f(x) != x:  </span><br><span class="line">        x = f(x)  </span><br><span class="line">    <span class="keyword">return</span> x  </span><br><span class="line">  </span><br><span class="line"><span class="keyword">def</span> <span class="title function_">g</span>(<span class="params">y</span>):  </span><br><span class="line">    <span class="keyword">return</span> (y + <span class="number">5</span>) // <span class="number">3</span></span><br></pre></td></tr></table></figure>
<p><img src="/2023/11/08/CS61A%E5%AD%A6%E4%B9%A0%E7%AC%94%E8%AE%B0/Pasted%20image%2020230708150326.png"></p>
<h2 id="Environments-for-Nested-Definitions"><a href="#Environments-for-Nested-Definitions" class="headerlink" title="Environments for Nested Definitions"></a><em>Environments for Nested Definitions</em></h2><p><img src="/2023/11/08/CS61A%E5%AD%A6%E4%B9%A0%E7%AC%94%E8%AE%B0/Pasted%20image%2020230708151420.png"><img src="/2023/11/08/CS61A%E5%AD%A6%E4%B9%A0%E7%AC%94%E8%AE%B0/Pasted%20image%2020230708151721.png"></p>
<figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">def</span> <span class="title function_">make_adder</span>(<span class="params">n</span>):  </span><br><span class="line">    <span class="keyword">def</span> <span class="title function_">adder</span>(<span class="params">k</span>):  </span><br><span class="line">        <span class="keyword">return</span> k + n  </span><br><span class="line">    <span class="keyword">return</span> adder</span><br></pre></td></tr></table></figure>
<ul>
<li>每一个创建的函数，它自身在哪个框架中创建，他的母函数就是那个框架的函数，在寻找变量值时，沿母函数层层向上搜寻知道全局框架，最先搜索到的值便是函数调用的值[[#^a02dcd]]</li>
</ul>
<h2 id="Local-Names"><a href="#Local-Names" class="headerlink" title="Local Names"></a><em>Local Names</em></h2><p><img src="/2023/11/08/CS61A%E5%AD%A6%E4%B9%A0%E7%AC%94%E8%AE%B0/Pasted%20image%2020230708214014.png"></p>
<ul>
<li>在嵌套定义中，母函数的形参可以在子函数中使用；而在相对独立的函数定义中一个函数无法找到和调用在另一个函数中定义的形参。</li>
</ul>
<h2 id="Lambda-Expressions"><a href="#Lambda-Expressions" class="headerlink" title="Lambda Expressions"></a><em>Lambda Expressions</em></h2><h3 id="1-lambda表达式相关"><a href="#1-lambda表达式相关" class="headerlink" title="1. lambda表达式相关"></a>1. lambda表达式相关</h3><p><img src="/2023/11/08/CS61A%E5%AD%A6%E4%B9%A0%E7%AC%94%E8%AE%B0/Pasted%20image%2020230708215032.png"></p>
<ul>
<li>lambda表达式是一个计算结果可以用某种方式解释的函数的表达式，当square被定义为“x * x”时，square仅仅作为一个数值存在；而当square被定义为一个关于x的lambda函数，它变成了一个具有具体调用地址的函数（甚至可以不定义lambda返回函数的名称而直接赋予形参具体值）</li>
<li>lambda：A function with formal parameter x that returns the value of “x * x”</li>
<li><font color="red"><big><strong>No Return!!!</strong></big></font></li>
<li>只能将单个表达式作为lambda函数的主体</li>
</ul>
<h3 id="2-lambda与def定义函数的区别"><a href="#2-lambda与def定义函数的区别" class="headerlink" title="2. lambda与def定义函数的区别"></a>2. lambda与def定义函数的区别</h3><ul>
<li>使用lambda定义时函数名为”lambda“形式的函数，而def语句定义函数名则为编程者赋予的函数名称，如下：<br><img src="/2023/11/08/CS61A%E5%AD%A6%E4%B9%A0%E7%AC%94%E8%AE%B0/Pasted%20image%2020230708220818.png"><br><img src="/2023/11/08/CS61A%E5%AD%A6%E4%B9%A0%E7%AC%94%E8%AE%B0/Pasted%20image%2020230708220836.png"><br><img src="/2023/11/08/CS61A%E5%AD%A6%E4%B9%A0%E7%AC%94%E8%AE%B0/Pasted%20image%2020230708221101.png"></li>
</ul>
<h2 id="Self-Reference"><a href="#Self-Reference" class="headerlink" title="Self-Reference"></a><em>Self-Reference</em></h2><figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">def</span> <span class="title function_">print_sums</span>(<span class="params">x</span>):  </span><br><span class="line">    <span class="built_in">print</span>(x)  </span><br><span class="line">    <span class="keyword">def</span> <span class="title function_">next_sum</span>(<span class="params">y</span>):  </span><br><span class="line">        <span class="keyword">return</span> print_sums(x + y)  </span><br><span class="line">    <span class="keyword">return</span> next_sum</span><br></pre></td></tr></table></figure>
<p><img src="/2023/11/08/CS61A%E5%AD%A6%E4%B9%A0%E7%AC%94%E8%AE%B0/Pasted%20image%2020230709005548.png"><br><img src="/2023/11/08/CS61A%E5%AD%A6%E4%B9%A0%E7%AC%94%E8%AE%B0/Pasted%20image%2020230709005813.png"></p>
<ul>
<li>(好难解释md)第一次调用的参数是1-&gt;n,打印1，定义next_sum函数，调用3-&gt;k，这时第一次调用的print_sums函数返回next_sum函数，而next_sum函数返回print_sums(n+k–&gt;1+3)，即返回print_sums(4)，然后先打印4…</li>
</ul>
<h2 id="Lab02-Higher-Order-Functions-Lambda-Expressions-Self-Reference"><a href="#Lab02-Higher-Order-Functions-Lambda-Expressions-Self-Reference" class="headerlink" title="Lab02: Higher-Order Functions, Lambda Expressions, Self Reference"></a><em>Lab02: Higher-Order Functions, Lambda Expressions, Self Reference</em></h2><h3 id="Q1-WWPD-Lambda-the-Free"><a href="#Q1-WWPD-Lambda-the-Free" class="headerlink" title="Q1: WWPD Lambda the Free"></a>Q1: WWPD Lambda the Free</h3><ul>
<li><input disabled type="checkbox"> 这个是真整体不咋理解，感觉没明白函数定义和返回，让我们过会来求助一波chatGPT老师（bushi）<figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br></pre></td><td class="code"><pre><span class="line"><span class="meta">&gt;&gt;&gt; </span><span class="keyword">def</span> <span class="title function_">cake</span>():</span><br><span class="line"><span class="meta">... </span>    <span class="built_in">print</span>(<span class="string">&#x27;beets&#x27;</span>) </span><br><span class="line"><span class="meta">... </span>    <span class="keyword">def</span> <span class="title function_">pie</span>():</span><br><span class="line"><span class="meta">... </span>        <span class="built_in">print</span>(<span class="string">&#x27;sweets&#x27;</span>) </span><br><span class="line"><span class="meta">... </span>        <span class="keyword">return</span> <span class="string">&#x27;cake&#x27;</span> </span><br><span class="line"><span class="meta">... </span>    <span class="keyword">return</span> pie </span><br><span class="line"><span class="meta">&gt;&gt;&gt; </span>chocolate = cake()</span><br><span class="line">beets</span><br><span class="line"><span class="meta">&gt;&gt;&gt; </span>chocolate</span><br><span class="line">Function</span><br><span class="line"><span class="meta">&gt;&gt;&gt; </span>chocolate()</span><br><span class="line">sweets</span><br><span class="line"><span class="string">&#x27;cake&#x27;</span></span><br><span class="line"><span class="meta">&gt;&gt;&gt; </span>more_chocolate, more_cake = chocolate(), cake</span><br><span class="line">sweets</span><br><span class="line"><span class="meta">&gt;&gt;&gt; </span>more_chocolate</span><br><span class="line"><span class="string">&#x27;cake&#x27;</span></span><br><span class="line"><span class="meta">&gt;&gt;&gt; </span><span class="keyword">def</span> <span class="title function_">snake</span>(<span class="params">x, y</span>): </span><br><span class="line"><span class="meta">... </span>    <span class="keyword">if</span> cake == more_cake: </span><br><span class="line"><span class="meta">... </span>        <span class="keyword">return</span> chocolate </span><br><span class="line"><span class="meta">... </span>    <span class="keyword">else</span>: </span><br><span class="line"><span class="meta">... </span>        <span class="keyword">return</span> x + y </span><br><span class="line"><span class="meta">&gt;&gt;&gt; </span>snake(<span class="number">10</span>, <span class="number">20</span>)</span><br><span class="line">Function</span><br><span class="line"><span class="meta">&gt;&gt;&gt; </span>snake(<span class="number">10</span>, <span class="number">20</span>)()</span><br><span class="line">sweets</span><br><span class="line"><span class="string">&#x27;cake&#x27;</span></span><br><span class="line"><span class="meta">&gt;&gt;&gt; </span>cake = <span class="string">&#x27;cake&#x27;</span> </span><br><span class="line"><span class="meta">&gt;&gt;&gt; </span>snake(<span class="number">10</span>, <span class="number">20</span>)</span><br><span class="line"><span class="number">30</span></span><br></pre></td></tr></table></figure>
<img src="/2023/11/08/CS61A%E5%AD%A6%E4%B9%A0%E7%AC%94%E8%AE%B0/Pasted%20image%2020230711220439.png"></li>
<li>感觉这个和上面那个例子有点异曲同工，就是定义变量名并且调用函数就会返回return值，但变量名没任何用好像（）（啊看不懂看不懂学不明白烦死了）<figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br></pre></td><td class="code"><pre><span class="line"><span class="meta">&gt;&gt;&gt; </span>onethousand = print_lambda(<span class="number">1000</span>)</span><br><span class="line"><span class="number">1000</span></span><br><span class="line"><span class="meta">&gt;&gt;&gt; </span>onethousand</span><br><span class="line">&gt;&gt;&gt;</span><br><span class="line"><span class="meta">&gt;&gt;&gt; </span>print_lambda</span><br><span class="line">&lt;function &lt;<span class="keyword">lambda</span>&gt; at <span class="number">0x000001752468AE60</span>&gt;</span><br></pre></td></tr></table></figure></li>
</ul>
<h3 id="Q3-Lambdas-and-Currying"><a href="#Q3-Lambdas-and-Currying" class="headerlink" title="Q3: Lambdas and Currying"></a>Q3: Lambdas and Currying</h3><ul>
<li>哇！感觉头一次发现到lambda到底是干嘛用的（一直觉得是个摆设），暂时的理解是用来调用未定义的参数（def和lambda如下）<ol>
<li>应用def调用：  <figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">def</span> <span class="title function_">lambda_curry2</span>(<span class="params">func</span>):  </span><br><span class="line">	<span class="keyword">def</span> <span class="title function_">function1</span>(<span class="params">x</span>):  </span><br><span class="line">	    <span class="keyword">def</span> <span class="title function_">function2</span>(<span class="params">y</span>):  </span><br><span class="line">	        <span class="keyword">return</span> func(x,y)  </span><br><span class="line">	    <span class="keyword">return</span> function2  </span><br><span class="line">	<span class="keyword">return</span> function1</span><br></pre></td></tr></table></figure></li>
<li>应用lambda调用：  <figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">def</span> <span class="title function_">lambda_curry2</span>(<span class="params">func</span>): </span><br><span class="line">   <span class="keyword">return</span> <span class="keyword">lambda</span> x : <span class="keyword">lambda</span> y : func(x , y)</span><br></pre></td></tr></table></figure>
  ^2f1599</li>
</ol>
</li>
</ul>
<h3 id="Q4-Count-van-Count"><a href="#Q4-Count-van-Count" class="headerlink" title="Q4: Count van Count"></a>Q4: Count van Count</h3><ul>
<li>单纯觉得这个求质数的方法很有启发性，算是第一次让我对函数封装有了相对具体的认识吧…<br>   就是先用count_factors函数计算出某个数的公约数，然后调用count_primes函数计算在n之内的所有质数的个数，其中调用is_prime函数利用count_factors函数判定是否符合质数条件（只有两个公约数）<figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">def</span> <span class="title function_">count_factors</span>(<span class="params">n</span>): </span><br><span class="line"><span class="string">&quot;&quot;&quot;Return the number of positive factors that n has. </span></span><br><span class="line"><span class="string"><span class="meta">&gt;&gt;&gt; </span>count_factors(6) </span></span><br><span class="line"><span class="string">4    # 1, 2, 3, 6 </span></span><br><span class="line"><span class="string"><span class="meta">&gt;&gt;&gt; </span>count_factors(4) </span></span><br><span class="line"><span class="string">3    # 1, 2, 4 </span></span><br><span class="line"><span class="string">&quot;&quot;&quot;</span> </span><br><span class="line">	i, count = <span class="number">1</span>, <span class="number">0</span> </span><br><span class="line">	<span class="keyword">while</span> i &lt;= n: </span><br><span class="line">		<span class="keyword">if</span> n % i == <span class="number">0</span>: </span><br><span class="line">			count += <span class="number">1</span> </span><br><span class="line">		i += <span class="number">1</span> </span><br><span class="line">	<span class="keyword">return</span> count </span><br><span class="line"></span><br><span class="line"><span class="keyword">def</span> <span class="title function_">count_primes</span>(<span class="params">n</span>): </span><br><span class="line"><span class="string">&quot;&quot;&quot;Return the number of prime numbers up to and including n. </span></span><br><span class="line"><span class="string"><span class="meta">&gt;&gt;&gt; </span>count_primes(6) </span></span><br><span class="line"><span class="string">3    # 2, 3, 5 </span></span><br><span class="line"><span class="string"><span class="meta">&gt;&gt;&gt; </span>count_primes(13) </span></span><br><span class="line"><span class="string">6    # 2, 3, 5, 7, 11, 13 </span></span><br><span class="line"><span class="string">&quot;&quot;&quot;</span> </span><br><span class="line">	i, count = <span class="number">1</span>, <span class="number">0</span> </span><br><span class="line">	<span class="keyword">while</span> i &lt;= n: </span><br><span class="line">		<span class="keyword">if</span> is_prime(i): </span><br><span class="line">			count += <span class="number">1</span></span><br><span class="line">		i += <span class="number">1</span> </span><br><span class="line">	<span class="keyword">return</span> count </span><br><span class="line"></span><br><span class="line"><span class="keyword">def</span> <span class="title function_">is_prime</span>(<span class="params">n</span>): </span><br><span class="line">	<span class="keyword">return</span> count_factors(n) == <span class="number">2</span> <span class="comment"># only factors are 1 and n</span></span><br></pre></td></tr></table></figure></li>
<li>暂时粗浅理解一下函数式编程吧，就是主函数的返回值尽可能都是一个函数，而调用一个主函数定义中没有显示的参数就要应用def或者lambda语句调用<figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br><span class="line">32</span><br><span class="line">33</span><br><span class="line">34</span><br><span class="line">35</span><br><span class="line">36</span><br><span class="line">37</span><br></pre></td><td class="code"><pre><span class="line">    <span class="string">&quot;&quot;&quot;Returns a function with one parameter N that counts all the numbers from 1 to N that satisfy the two-argument predicate function Condition, where the first argument for Condition is N and the second argument is the number from 1 to N.</span></span><br><span class="line"><span class="string"></span></span><br><span class="line"><span class="string">    &gt;&gt;&gt; count_factors = count_cond(lambda n, i: n % i == 0)</span></span><br><span class="line"><span class="string">    &gt;&gt;&gt; count_factors(2)   # 1, 2</span></span><br><span class="line"><span class="string">    2</span></span><br><span class="line"><span class="string">    &gt;&gt;&gt; count_factors(4)   # 1, 2, 4</span></span><br><span class="line"><span class="string">    3</span></span><br><span class="line"><span class="string">    &gt;&gt;&gt; count_factors(12)  # 1, 2, 3, 4, 6, 12</span></span><br><span class="line"><span class="string">    6</span></span><br><span class="line"><span class="string"></span></span><br><span class="line"><span class="string">    &gt;&gt;&gt; is_prime = lambda n, i: count_factors(i) == 2</span></span><br><span class="line"><span class="string">    &gt;&gt;&gt; count_primes = count_cond(is_prime)</span></span><br><span class="line"><span class="string">    &gt;&gt;&gt; count_primes(2)    # 2</span></span><br><span class="line"><span class="string">    1</span></span><br><span class="line"><span class="string">    &gt;&gt;&gt; count_primes(3)    # 2, 3</span></span><br><span class="line"><span class="string">    2</span></span><br><span class="line"><span class="string">    &gt;&gt;&gt; count_primes(4)    # 2, 3</span></span><br><span class="line"><span class="string">    2</span></span><br><span class="line"><span class="string">    &gt;&gt;&gt; count_primes(5)    # 2, 3, 5</span></span><br><span class="line"><span class="string">    3</span></span><br><span class="line"><span class="string">    &gt;&gt;&gt; count_primes(20)   # 2, 3, 5, 7, 11, 13, 17, 19</span></span><br><span class="line"><span class="string">    8</span></span><br><span class="line"><span class="string">    &quot;&quot;&quot;</span></span><br><span class="line"><span class="keyword">def</span> <span class="title function_">count_cond</span>(<span class="params">condition</span>):</span><br><span class="line">    <span class="keyword">return</span> <span class="keyword">lambda</span> x: <span class="built_in">sum</span>(<span class="number">1</span> <span class="keyword">for</span> y <span class="keyword">in</span> <span class="built_in">range</span>(<span class="number">1</span>, x+<span class="number">1</span>) <span class="keyword">if</span> condition(x, y))</span><br><span class="line"><span class="comment">#这种方式用lambda函数，将condition(x,y)作为参数传给lambda，lambda函数接收一个参数x，然后使用range(1, x+1)生成从1到x的数字，对于每个数字y，如果满足条件condition(x, y)，则计数加1。最后，返回计数结果的总和。</span></span><br><span class="line"></span><br><span class="line"><span class="keyword">def</span> <span class="title function_">count_cond</span>(<span class="params">condition</span>):</span><br><span class="line">	<span class="keyword">def</span> <span class="title function_">count_f</span>(<span class="params">x</span>):</span><br><span class="line">		i,count = <span class="number">1</span>,<span class="number">0</span></span><br><span class="line">		<span class="keyword">while</span> i &lt; x:</span><br><span class="line">			<span class="keyword">if</span> condition(x,i):</span><br><span class="line">				count += <span class="number">1</span></span><br><span class="line">			i += <span class="number">1</span></span><br><span class="line">		<span class="keyword">return</span> count</span><br><span class="line">	<span class="keyword">return</span> count_f</span><br><span class="line"><span class="comment">#这种方式用def定义函数(个人认为更好理解一点)，注意返回值还是要一个函数而不是直接count（报错：NoneType那个）</span></span><br></pre></td></tr></table></figure>
^ecfc38</li>
</ul>
<h3 id="Q5-Both-Paths"><a href="#Q5-Both-Paths" class="headerlink" title="Q5: Both Paths"></a>Q5: Both Paths</h3><ul>
<li>关于局部变量(<code>nonlocal</code>)和全局变量(<code>global</code>)<ol>
<li>全局变量和局部变量（global和nonlocal）<figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br></pre></td><td class="code"><pre><span class="line">g = <span class="number">0</span>  </span><br><span class="line"><span class="keyword">def</span> <span class="title function_">global_test</span>(): </span><br><span class="line">	<span class="comment">#global g</span></span><br><span class="line">    g += <span class="number">1</span>  </span><br><span class="line">    <span class="built_in">print</span>(g)</span><br><span class="line"><span class="meta">&gt;&gt;&gt; </span>global_test</span><br><span class="line"><span class="meta">&gt;&gt;&gt; </span>UnboundLocalError: local variable <span class="string">&#x27;gcount&#x27;</span> referenced before assignment</span><br></pre></td></tr></table></figure>
<figure class="highlight plaintext"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br><span class="line">32</span><br><span class="line">33</span><br><span class="line">34</span><br><span class="line">35</span><br><span class="line">36</span><br><span class="line">37</span><br><span class="line">38</span><br><span class="line">39</span><br><span class="line">40</span><br><span class="line">41</span><br><span class="line">42</span><br><span class="line">43</span><br><span class="line">44</span><br><span class="line">45</span><br><span class="line">46</span><br><span class="line">47</span><br><span class="line">48</span><br><span class="line">49</span><br><span class="line">50</span><br><span class="line">51</span><br><span class="line">52</span><br><span class="line">53</span><br><span class="line">54</span><br><span class="line">55</span><br><span class="line">56</span><br><span class="line">57</span><br><span class="line">58</span><br><span class="line">59</span><br><span class="line">60</span><br><span class="line">61</span><br><span class="line">62</span><br><span class="line">63</span><br><span class="line">64</span><br><span class="line">65</span><br><span class="line">66</span><br><span class="line">67</span><br><span class="line">68</span><br><span class="line">69</span><br><span class="line">70</span><br><span class="line">71</span><br><span class="line">72</span><br><span class="line">73</span><br><span class="line">74</span><br><span class="line">75</span><br><span class="line">76</span><br><span class="line">77</span><br><span class="line">78</span><br><span class="line">79</span><br><span class="line">80</span><br><span class="line">81</span><br><span class="line">82</span><br><span class="line">83</span><br><span class="line">84</span><br><span class="line">85</span><br><span class="line">86</span><br><span class="line">87</span><br><span class="line">88</span><br><span class="line">89</span><br><span class="line">90</span><br><span class="line">91</span><br><span class="line">92</span><br><span class="line">93</span><br><span class="line">94</span><br><span class="line">95</span><br><span class="line">96</span><br><span class="line">97</span><br><span class="line">98</span><br><span class="line">99</span><br><span class="line">100</span><br><span class="line">101</span><br><span class="line">102</span><br><span class="line">103</span><br><span class="line">104</span><br><span class="line">105</span><br><span class="line">106</span><br><span class="line">107</span><br><span class="line">108</span><br><span class="line">109</span><br><span class="line">110</span><br><span class="line">111</span><br><span class="line">112</span><br><span class="line">113</span><br><span class="line">114</span><br><span class="line">115</span><br><span class="line">116</span><br><span class="line">117</span><br><span class="line">118</span><br><span class="line">119</span><br><span class="line">120</span><br><span class="line">121</span><br><span class="line">122</span><br><span class="line">123</span><br><span class="line">124</span><br><span class="line">125</span><br><span class="line">126</span><br><span class="line">127</span><br><span class="line">128</span><br><span class="line">129</span><br><span class="line">130</span><br><span class="line">131</span><br><span class="line">132</span><br><span class="line">133</span><br><span class="line">134</span><br><span class="line">135</span><br><span class="line">136</span><br><span class="line">137</span><br><span class="line">138</span><br><span class="line">139</span><br><span class="line">140</span><br><span class="line">141</span><br><span class="line">142</span><br><span class="line">143</span><br><span class="line">144</span><br><span class="line">145</span><br><span class="line">146</span><br><span class="line">147</span><br><span class="line">148</span><br><span class="line">149</span><br><span class="line">150</span><br><span class="line">151</span><br><span class="line">152</span><br><span class="line">153</span><br><span class="line">154</span><br><span class="line">155</span><br><span class="line">156</span><br><span class="line">157</span><br><span class="line">158</span><br><span class="line">159</span><br><span class="line">160</span><br><span class="line">161</span><br><span class="line">162</span><br><span class="line">163</span><br><span class="line">164</span><br><span class="line">165</span><br><span class="line">166</span><br><span class="line">167</span><br><span class="line">168</span><br><span class="line">169</span><br><span class="line">170</span><br><span class="line">171</span><br><span class="line">172</span><br><span class="line">173</span><br><span class="line">174</span><br><span class="line">175</span><br><span class="line">176</span><br><span class="line">177</span><br><span class="line">178</span><br><span class="line">179</span><br><span class="line">180</span><br><span class="line">181</span><br><span class="line">182</span><br><span class="line">183</span><br><span class="line">184</span><br><span class="line">185</span><br><span class="line">186</span><br><span class="line">187</span><br><span class="line">188</span><br><span class="line">189</span><br><span class="line">190</span><br><span class="line">191</span><br><span class="line">192</span><br><span class="line">193</span><br><span class="line">194</span><br><span class="line">195</span><br><span class="line">196</span><br><span class="line">197</span><br><span class="line">198</span><br><span class="line">199</span><br><span class="line">200</span><br><span class="line">201</span><br><span class="line">202</span><br><span class="line">203</span><br><span class="line">204</span><br><span class="line">205</span><br><span class="line">206</span><br><span class="line">207</span><br><span class="line">208</span><br><span class="line">209</span><br><span class="line">210</span><br><span class="line">211</span><br><span class="line">212</span><br><span class="line">213</span><br><span class="line">214</span><br><span class="line">215</span><br><span class="line">216</span><br><span class="line">217</span><br><span class="line">218</span><br><span class="line">219</span><br><span class="line">220</span><br><span class="line">221</span><br><span class="line">222</span><br><span class="line">223</span><br><span class="line">224</span><br><span class="line">225</span><br><span class="line">226</span><br><span class="line">227</span><br><span class="line">228</span><br><span class="line">229</span><br><span class="line">230</span><br><span class="line">231</span><br><span class="line">232</span><br><span class="line">233</span><br><span class="line">234</span><br><span class="line">235</span><br><span class="line">236</span><br><span class="line">237</span><br><span class="line">238</span><br><span class="line">239</span><br><span class="line">240</span><br><span class="line">241</span><br><span class="line">242</span><br><span class="line">243</span><br><span class="line">244</span><br><span class="line">245</span><br><span class="line">246</span><br><span class="line">247</span><br><span class="line">248</span><br><span class="line">249</span><br><span class="line">250</span><br><span class="line">251</span><br><span class="line">252</span><br><span class="line">253</span><br><span class="line">254</span><br><span class="line">255</span><br><span class="line">256</span><br><span class="line">257</span><br><span class="line">258</span><br><span class="line">259</span><br><span class="line">260</span><br><span class="line">261</span><br><span class="line">262</span><br><span class="line">263</span><br><span class="line">264</span><br><span class="line">265</span><br><span class="line">266</span><br><span class="line">267</span><br><span class="line">268</span><br><span class="line">269</span><br><span class="line">270</span><br><span class="line">271</span><br><span class="line">272</span><br><span class="line">273</span><br><span class="line">274</span><br><span class="line">275</span><br><span class="line">276</span><br><span class="line">277</span><br><span class="line">278</span><br><span class="line">279</span><br><span class="line">280</span><br><span class="line">281</span><br><span class="line">282</span><br><span class="line">283</span><br><span class="line">284</span><br><span class="line">285</span><br><span class="line">286</span><br><span class="line">287</span><br><span class="line">288</span><br><span class="line">289</span><br><span class="line">290</span><br><span class="line">291</span><br><span class="line">292</span><br><span class="line">293</span><br><span class="line">294</span><br><span class="line">295</span><br><span class="line">296</span><br><span class="line">297</span><br><span class="line">298</span><br><span class="line">299</span><br><span class="line">300</span><br><span class="line">301</span><br><span class="line">302</span><br><span class="line">303</span><br><span class="line">304</span><br><span class="line">305</span><br><span class="line">306</span><br><span class="line">307</span><br><span class="line">308</span><br><span class="line">309</span><br><span class="line">310</span><br><span class="line">311</span><br><span class="line">312</span><br><span class="line">313</span><br><span class="line">314</span><br><span class="line">315</span><br><span class="line">316</span><br><span class="line">317</span><br><span class="line">318</span><br><span class="line">319</span><br><span class="line">320</span><br><span class="line">321</span><br><span class="line">322</span><br><span class="line">323</span><br><span class="line">324</span><br><span class="line">325</span><br><span class="line">326</span><br><span class="line">327</span><br><span class="line">328</span><br><span class="line">329</span><br><span class="line">330</span><br><span class="line">331</span><br><span class="line">332</span><br><span class="line">333</span><br><span class="line">334</span><br><span class="line">335</span><br><span class="line">336</span><br><span class="line">337</span><br><span class="line">338</span><br><span class="line">339</span><br><span class="line">340</span><br><span class="line">341</span><br><span class="line">342</span><br><span class="line">343</span><br><span class="line">344</span><br><span class="line">345</span><br><span class="line">346</span><br><span class="line">347</span><br><span class="line">348</span><br><span class="line">349</span><br><span class="line">350</span><br><span class="line">351</span><br><span class="line">352</span><br><span class="line">353</span><br><span class="line">354</span><br><span class="line">355</span><br><span class="line">356</span><br><span class="line">357</span><br><span class="line">358</span><br><span class="line">359</span><br><span class="line">360</span><br><span class="line">361</span><br><span class="line">362</span><br><span class="line">363</span><br><span class="line">364</span><br><span class="line">365</span><br><span class="line">366</span><br><span class="line">367</span><br><span class="line">368</span><br><span class="line">369</span><br><span class="line">370</span><br><span class="line">371</span><br><span class="line">372</span><br><span class="line">373</span><br><span class="line">374</span><br><span class="line">375</span><br><span class="line">376</span><br><span class="line">377</span><br><span class="line">378</span><br><span class="line">379</span><br><span class="line">380</span><br><span class="line">381</span><br><span class="line">382</span><br><span class="line">383</span><br><span class="line">384</span><br><span class="line">385</span><br><span class="line">386</span><br><span class="line">387</span><br><span class="line">388</span><br><span class="line">389</span><br><span class="line">390</span><br><span class="line">391</span><br><span class="line">392</span><br><span class="line">393</span><br><span class="line">394</span><br><span class="line">395</span><br><span class="line">396</span><br><span class="line">397</span><br><span class="line">398</span><br><span class="line">399</span><br><span class="line">400</span><br><span class="line">401</span><br><span class="line">402</span><br><span class="line">403</span><br><span class="line">404</span><br><span class="line">405</span><br><span class="line">406</span><br><span class="line">407</span><br><span class="line">408</span><br><span class="line">409</span><br><span class="line">410</span><br><span class="line">411</span><br><span class="line">412</span><br><span class="line">413</span><br><span class="line">414</span><br><span class="line">415</span><br><span class="line">416</span><br><span class="line">417</span><br><span class="line">418</span><br><span class="line">419</span><br><span class="line">420</span><br><span class="line">421</span><br><span class="line">422</span><br><span class="line">423</span><br><span class="line">424</span><br><span class="line">425</span><br><span class="line">426</span><br><span class="line">427</span><br><span class="line">428</span><br><span class="line">429</span><br><span class="line">430</span><br><span class="line">431</span><br><span class="line">432</span><br><span class="line">433</span><br><span class="line">434</span><br><span class="line">435</span><br><span class="line">436</span><br><span class="line">437</span><br><span class="line">438</span><br><span class="line">439</span><br><span class="line">440</span><br><span class="line">441</span><br><span class="line">442</span><br><span class="line">443</span><br><span class="line">444</span><br><span class="line">445</span><br><span class="line">446</span><br><span class="line">447</span><br><span class="line">448</span><br><span class="line">449</span><br><span class="line">450</span><br><span class="line">451</span><br><span class="line">452</span><br><span class="line">453</span><br><span class="line">454</span><br><span class="line">455</span><br><span class="line">456</span><br><span class="line">457</span><br><span class="line">458</span><br><span class="line">459</span><br><span class="line">460</span><br><span class="line">461</span><br><span class="line">462</span><br><span class="line">463</span><br><span class="line">464</span><br><span class="line">465</span><br><span class="line">466</span><br><span class="line">467</span><br><span class="line">468</span><br><span class="line">469</span><br><span class="line">470</span><br><span class="line">471</span><br><span class="line">472</span><br><span class="line">473</span><br><span class="line">474</span><br><span class="line">475</span><br><span class="line">476</span><br><span class="line">477</span><br><span class="line">478</span><br><span class="line">479</span><br><span class="line">480</span><br><span class="line">481</span><br><span class="line">482</span><br><span class="line">483</span><br><span class="line">484</span><br><span class="line">485</span><br><span class="line">486</span><br><span class="line">487</span><br><span class="line">488</span><br><span class="line">489</span><br><span class="line">490</span><br><span class="line">491</span><br><span class="line">492</span><br><span class="line">493</span><br><span class="line">494</span><br><span class="line">495</span><br><span class="line">496</span><br><span class="line">497</span><br><span class="line">498</span><br><span class="line">499</span><br><span class="line">500</span><br><span class="line">501</span><br><span class="line">502</span><br><span class="line">503</span><br><span class="line">504</span><br><span class="line">505</span><br><span class="line">506</span><br><span class="line">507</span><br><span class="line">508</span><br><span class="line">509</span><br><span class="line">510</span><br><span class="line">511</span><br><span class="line">512</span><br><span class="line">513</span><br><span class="line">514</span><br><span class="line">515</span><br><span class="line">516</span><br><span class="line">517</span><br><span class="line">518</span><br><span class="line">519</span><br><span class="line">520</span><br><span class="line">521</span><br><span class="line">522</span><br><span class="line">523</span><br><span class="line">524</span><br><span class="line">525</span><br><span class="line">526</span><br><span class="line">527</span><br><span class="line">528</span><br><span class="line">529</span><br><span class="line">530</span><br><span class="line">531</span><br><span class="line">532</span><br><span class="line">533</span><br><span class="line">534</span><br><span class="line">535</span><br><span class="line">536</span><br><span class="line">537</span><br><span class="line">538</span><br><span class="line">539</span><br><span class="line">540</span><br><span class="line">541</span><br><span class="line">542</span><br><span class="line">543</span><br><span class="line">544</span><br><span class="line">545</span><br><span class="line">546</span><br><span class="line">547</span><br><span class="line">548</span><br><span class="line">549</span><br><span class="line">550</span><br><span class="line">551</span><br><span class="line">552</span><br><span class="line">553</span><br><span class="line">554</span><br><span class="line">555</span><br><span class="line">556</span><br><span class="line">557</span><br><span class="line">558</span><br><span class="line">559</span><br><span class="line">560</span><br><span class="line">561</span><br><span class="line">562</span><br><span class="line">563</span><br><span class="line">564</span><br><span class="line">565</span><br><span class="line">566</span><br><span class="line">567</span><br><span class="line">568</span><br><span class="line">569</span><br><span class="line">570</span><br><span class="line">571</span><br><span class="line">572</span><br><span class="line">573</span><br><span class="line">574</span><br><span class="line">575</span><br><span class="line">576</span><br><span class="line">577</span><br><span class="line">578</span><br><span class="line">579</span><br><span class="line">580</span><br><span class="line">581</span><br><span class="line">582</span><br><span class="line">583</span><br><span class="line">584</span><br><span class="line">585</span><br><span class="line">586</span><br><span class="line">587</span><br><span class="line">588</span><br><span class="line">589</span><br><span class="line">590</span><br><span class="line">591</span><br><span class="line">592</span><br><span class="line">593</span><br><span class="line">594</span><br><span class="line">595</span><br><span class="line">596</span><br><span class="line">597</span><br><span class="line">598</span><br><span class="line">599</span><br><span class="line">600</span><br><span class="line">601</span><br><span class="line">602</span><br><span class="line">603</span><br><span class="line">604</span><br><span class="line">605</span><br><span class="line">606</span><br><span class="line">607</span><br><span class="line">608</span><br><span class="line">609</span><br><span class="line">610</span><br><span class="line">611</span><br><span class="line">612</span><br><span class="line">613</span><br><span class="line">614</span><br><span class="line">615</span><br><span class="line">616</span><br><span class="line">617</span><br><span class="line">618</span><br><span class="line">619</span><br><span class="line">620</span><br><span class="line">621</span><br><span class="line">622</span><br><span class="line">623</span><br><span class="line">624</span><br><span class="line">625</span><br><span class="line">626</span><br><span class="line">627</span><br><span class="line">628</span><br><span class="line">629</span><br><span class="line">630</span><br><span class="line">631</span><br><span class="line">632</span><br><span class="line">633</span><br><span class="line">634</span><br><span class="line">635</span><br><span class="line">636</span><br><span class="line">637</span><br><span class="line">638</span><br><span class="line">639</span><br><span class="line">640</span><br><span class="line">641</span><br><span class="line">642</span><br><span class="line">643</span><br><span class="line">644</span><br><span class="line">645</span><br><span class="line">646</span><br><span class="line">647</span><br><span class="line">648</span><br><span class="line">649</span><br><span class="line">650</span><br><span class="line">651</span><br><span class="line">652</span><br><span class="line">653</span><br><span class="line">654</span><br><span class="line">655</span><br><span class="line">656</span><br><span class="line">657</span><br><span class="line">658</span><br><span class="line">659</span><br><span class="line">660</span><br><span class="line">661</span><br><span class="line">662</span><br><span class="line">663</span><br><span class="line">664</span><br><span class="line">665</span><br><span class="line">666</span><br><span class="line">667</span><br><span class="line">668</span><br><span class="line">669</span><br><span class="line">670</span><br><span class="line">671</span><br><span class="line">672</span><br><span class="line">673</span><br><span class="line">674</span><br><span class="line">675</span><br><span class="line">676</span><br><span class="line">677</span><br><span class="line">678</span><br><span class="line">679</span><br><span class="line">680</span><br><span class="line">681</span><br><span class="line">682</span><br><span class="line">683</span><br><span class="line">684</span><br><span class="line">685</span><br><span class="line">686</span><br><span class="line">687</span><br><span class="line">688</span><br><span class="line">689</span><br><span class="line">690</span><br><span class="line">691</span><br><span class="line">692</span><br><span class="line">693</span><br><span class="line">694</span><br><span class="line">695</span><br><span class="line">696</span><br><span class="line">697</span><br><span class="line">698</span><br><span class="line">699</span><br><span class="line">700</span><br><span class="line">701</span><br><span class="line">702</span><br><span class="line">703</span><br><span class="line">704</span><br><span class="line">705</span><br><span class="line">706</span><br><span class="line">707</span><br><span class="line">708</span><br><span class="line">709</span><br><span class="line">710</span><br><span class="line">711</span><br><span class="line">712</span><br><span class="line">713</span><br><span class="line">714</span><br><span class="line">715</span><br><span class="line">716</span><br><span class="line">717</span><br><span class="line">718</span><br><span class="line">719</span><br><span class="line">720</span><br><span class="line">721</span><br><span class="line">722</span><br><span class="line">723</span><br><span class="line">724</span><br><span class="line">725</span><br><span class="line">726</span><br><span class="line">727</span><br><span class="line">728</span><br><span class="line">729</span><br><span class="line">730</span><br><span class="line">731</span><br><span class="line">732</span><br><span class="line">733</span><br></pre></td><td class="code"><pre><span class="line">~~~python</span><br><span class="line">def make_counter():</span><br><span class="line">    count = 0</span><br><span class="line">    def counter():</span><br><span class="line">        nonlocal count</span><br><span class="line">        count += 1</span><br><span class="line">        return count</span><br><span class="line">    return counter</span><br><span class="line">        </span><br><span class="line">def make_counter_test():</span><br><span class="line">	mc = make_counter()</span><br><span class="line">	print(mc())</span><br><span class="line">	print(mc())</span><br><span class="line">	print(mc())</span><br><span class="line">  </span><br><span class="line">make_counter_test()</span><br><span class="line">~~~</span><br><span class="line">  ```nonlocal```声明的变量不是局部变量,也不是全局变量,而是外部嵌套函数内的变量。</span><br><span class="line">- python可以设定给一个参数默认值，当该参数调用时没有值则按默认值计算，若有值输入则按输入值，例：</span><br><span class="line">~~~python</span><br><span class="line">def root(x, degree=2): </span><br><span class="line">	&quot;&quot;&quot;For example</span><br><span class="line">	&gt;&gt;&gt; root(64) </span><br><span class="line">	8 </span><br><span class="line">	&gt;&gt;&gt; root(64, 3) </span><br><span class="line">	4</span><br><span class="line">	&quot;&quot;&quot;</span><br><span class="line">	return x ** (1 / degree)</span><br><span class="line">~~~</span><br><span class="line">- [ ] 这个...真不知道该说啥，就是说一整个没看懂好吧，最后感觉上是emmmm就是往S后面加U&amp;D？</span><br><span class="line">~~~python</span><br><span class="line">def both_paths(sofar=&quot;S&quot;):  </span><br><span class="line">    &quot;&quot;&quot;  </span><br><span class="line">    &gt;&gt;&gt; up, down = both_paths()    </span><br><span class="line">    S    </span><br><span class="line">    &gt;&gt;&gt; upup, updown = up()</span><br><span class="line">	SU    </span><br><span class="line">	&gt;&gt;&gt; downup, downdown = down()</span><br><span class="line">	SD    </span><br><span class="line">	&gt;&gt;&gt; _ = upup()    </span><br><span class="line">	SUU    </span><br><span class="line">	&quot;&quot;&quot;    </span><br><span class="line">	&quot;*** YOUR CODE HERE ***&quot;  </span><br><span class="line">    upsofar = sofar  </span><br><span class="line">    downsofar = sofar  </span><br><span class="line">  </span><br><span class="line">    def up():  </span><br><span class="line">        nonlocal upsofar  </span><br><span class="line">        upsofar += &#x27;U&#x27;  </span><br><span class="line">        print(upsofar)  </span><br><span class="line">        return up, up  </span><br><span class="line">      </span><br><span class="line">    def down():  </span><br><span class="line">        nonlocal downsofar  </span><br><span class="line">        downsofar += &#x27;D&#x27;  </span><br><span class="line">        print(downsofar)  </span><br><span class="line">        return down , down  </span><br><span class="line">  </span><br><span class="line">    print(sofar)  </span><br><span class="line">    return up,down</span><br><span class="line">~~~</span><br><span class="line">### Q7: Lambda the Environment Diagram</span><br><span class="line">- [ ] 这个也理解不了一点呢~真好呢（精神状态逐渐扭曲xie），就从f3 21就看不懂了哭...</span><br><span class="line">~~~python</span><br><span class="line">a = lambda x: 2 * x + 1</span><br><span class="line">def b(b,x):</span><br><span class="line">	return b(x + a(x))</span><br><span class="line">&gt;&gt;&gt; x = 3</span><br><span class="line">&gt;&gt;&gt; b(a,x)</span><br><span class="line">&gt;&gt;&gt; 21</span><br><span class="line">~~~</span><br><span class="line">![](./CS61A学习笔记/Pasted%20image%2020230712213717.png)</span><br><span class="line"></span><br><span class="line">### Q8: Composite Identity Function</span><br><span class="line">- 这个函数名已经足够反映我此时的心理状态了好吧...就是要调用函数调用函数，不能直接返回个值，不管是什么类型，都要先定义个函数和他的返回值，再返回那个函数</span><br><span class="line">~~~python</span><br><span class="line">def composite_identity(f, g):  </span><br><span class="line">    def xiande(y):  </span><br><span class="line">        if compose1(f,g)(y) == compose1(g,f)(y):</span><br><span class="line">            return True  </span><br><span class="line">        else:  </span><br><span class="line">            return False  </span><br><span class="line">    return xiande</span><br><span class="line">~~~</span><br><span class="line">### Q9: I Heard You Liked Functions...</span><br><span class="line">- 好帅的递归，但不会(注意最后总函数的返回值缩进)</span><br><span class="line">  小小总结一下：就是这种1.2.3.1.2.3...类型的循环好像都可以用这种类型的递归，即定义一个函数（如本题的conmpose1），然后函数参数分别为当前值和下一个函数值，即```compose1(f2,cycle_f(n-1))```这种形式，之后再试试呐~</span><br><span class="line">~~~python</span><br><span class="line">def cycle(f1, f2, f3):  </span><br><span class="line">    def cycle_f(n):  </span><br><span class="line">        if n == 0:  </span><br><span class="line">            return lambda x : x  </span><br><span class="line">        elif n % 3 == 1:  </span><br><span class="line">            return compose1(f1,cycle_f(n-1))  </span><br><span class="line">        elif n % 3 == 2:  </span><br><span class="line">            return compose1(f2,cycle_f(n-1))  </span><br><span class="line">        else:  </span><br><span class="line">            return compose1(f3,cycle_f(n-1))  </span><br><span class="line">    return cycle_f</span><br><span class="line">~~~</span><br><span class="line">## *Midterm1 Review*</span><br><span class="line">- ```print```函数始终返回```None```，在它被当作函数调用时同时输出他的参数（以空格分开）![](./CS61A学习笔记/Pasted%20image%2020230713091350.png)</span><br><span class="line">- 一个验证函数在调用参数时总是沿母函数层层相上搜索的例子，如下：我觉得最重要的一步理解就是```pirate```函数里调用的```arggg```是3，而真正应用于返回函数```plunder```的参数实际上是已经定义的```square```函数，因此本质上```add```的第一项就是4的平方![](./CS61A学习笔记/Pasted%20image%2020230713100856.png) ^a02dcd</span><br><span class="line">~~~python</span><br><span class="line">from operator import add,mul</span><br><span class="line">def square(x):</span><br><span class="line">    return mul(x,x)</span><br><span class="line">    </span><br><span class="line">def pirate(arggg):</span><br><span class="line">    print(&#x27;matey&#x27;)</span><br><span class="line">    def plunder(arggg):</span><br><span class="line">        return arggg</span><br><span class="line">    return plunder</span><br><span class="line">    </span><br><span class="line">add(pirate(3)(square)(4),1)</span><br><span class="line">~~~</span><br><span class="line">## *Decorations*</span><br><span class="line">- 好像就是一个可以追踪高级函数运行过程的小玩意，但我的ucb不知道为什么运行不了（好像没装上这个库）</span><br><span class="line">~~~python</span><br><span class="line">def trace(fn):  </span><br><span class="line">    def traced(x):  </span><br><span class="line">        print(&#x27;Calling&#x27;,fn,&#x27;on argument&#x27;,x)  </span><br><span class="line">        return fn(x)  </span><br><span class="line">    return traced  </span><br><span class="line">  </span><br><span class="line">@trace  </span><br><span class="line">def square(x):  </span><br><span class="line">    return x * x  </span><br><span class="line">@trace  </span><br><span class="line">def sum_squares_up_to(n):  </span><br><span class="line">    k = 1  </span><br><span class="line">    total = 0  </span><br><span class="line">    while k &lt;= n:  </span><br><span class="line">        total,k = total + square(k),k + 1  </span><br><span class="line">    return total</span><br><span class="line">&quot;&quot;&quot;</span><br><span class="line">&gt;&gt;&gt; square(2)</span><br><span class="line">Calling &lt;function square at 0x0000015003B8ADD0&gt; on argument 2</span><br><span class="line">4</span><br><span class="line">&gt;&gt;&gt; sum_squares_up_to(5)</span><br><span class="line">Calling &lt;function sum_squares_up_to at 0x0000015003B8AE60&gt; on argument 5</span><br><span class="line">Calling &lt;function square at 0x0000015003B8ADD0&gt; on argument 1</span><br><span class="line">Calling &lt;function square at 0x0000015003B8ADD0&gt; on argument 2</span><br><span class="line">Calling &lt;function square at 0x0000015003B8ADD0&gt; on argument 3</span><br><span class="line">Calling &lt;function square at 0x0000015003B8ADD0&gt; on argument 4</span><br><span class="line">Calling &lt;function square at 0x0000015003B8ADD0&gt; on argument 5</span><br><span class="line">55</span><br><span class="line">&quot;&quot;&quot;</span><br><span class="line">~~~</span><br><span class="line"></span><br><span class="line"># Lecture 6: Recursion（递归）</span><br><span class="line">## *Recursive functions*</span><br><span class="line">- 递归的基本思路：首先具备一个```基本情况(basic case)```，然后在更复杂的函数求解过程中应用自身函数不断简化所求，使其更接近```基本情况(basic case)```</span><br><span class="line">~~~python #求各位之和（用递归）</span><br><span class="line">def split(n):  </span><br><span class="line">    return n // 10, n % 10  </span><br><span class="line">  </span><br><span class="line">def sum_digits(n):  #basic case</span><br><span class="line">    if n &lt; 10:  </span><br><span class="line">        return n  </span><br><span class="line">    else:  </span><br><span class="line">        all_but_last, last = split(n)  </span><br><span class="line">        return sum_digits(all_but_last) + last</span><br><span class="line">~~~</span><br><span class="line">## *Recursion in Environment Diagrams*</span><br><span class="line">- 对比来看，应用```while```循环需要定义参数来进行跟踪统计，而运用递归则只需要计算机分不同框架来自动区分递归的步骤（参数少） ^5ca33e</span><br><span class="line">~~~python</span><br><span class="line">def fact_iter(n):</span><br><span class="line">	total, k = 1, 1</span><br><span class="line">	while k &lt;= n:</span><br><span class="line">		total, k = total * k, k + 1</span><br><span class="line">	return total</span><br><span class="line"></span><br><span class="line">def fact(n):</span><br><span class="line">	if n == 0:</span><br><span class="line">		return 1</span><br><span class="line">	else:</span><br><span class="line">		return n * fact(n-1)</span><br><span class="line">~~~</span><br><span class="line">## Verifying Recursive Functions</span><br><span class="line">&lt;small&gt;老师管做递归叫信仰之跃(The Recursive Leap of Faith)笑死我了哈哈哈哈哈&lt;/small&gt;</span><br><span class="line">- 验证递归是否符合要求的步骤：[[#^5ca33e]]</span><br><span class="line">  1. Verify the base case. 验证基本情况（确定有一个情况是正确的）</span><br><span class="line">  2. Treat``` fact``` as a functional abstraction. 将函数看作一个函数抽象功能，不考虑这个函数如何实施，只考虑它会做什么（好抽象...）</span><br><span class="line">  3. Assume that ```fact(n-1)``` is correct. 假设```fact(n)```递归返回的第一个值```fact(n-1)```是正确的</span><br><span class="line">  4. Verify that ```fact(n)``` is correct, assuming that ```fact(n-1)``` correct</span><br><span class="line">  5. 代代特值（bushi）</span><br><span class="line">## *Mutual Recursion*</span><br><span class="line">### &lt;small&gt;Example: The Luhn algorithm&lt;/small&gt;</span><br><span class="line">- 感觉需要先给未来1000%看不懂这个例子是啥的我解释一下，就是一个现在国际上很通用的验证一些卡号的方法，具体如下：</span><br><span class="line">  1. 从右向左，从最右面第一个数字开始乘一，右起第二个数乘二，第三个数乘三...以此类推</span><br><span class="line">  2. 如果经过乘法运算后所得小于十则直接保留，如果大于十就返回其所得值的每位数字之和（如2 * 8 = 16则返回1 + 6 = 7）</span><br><span class="line">  3. 将整个号码每位返回值相加并且取10的余数即被称为判定位</span><br><span class="line">  ![](./CS61A学习笔记/Pasted%20image%2020230714014717.png)</span><br><span class="line">- 所以这个例子应用交互递归的点就在于一位数✖1另一位数✖2，因此需要两个分别为乘一乘二的函数的返回值都是彼此以达到变换效果</span><br><span class="line">^756591</span><br><span class="line">~~~python</span><br><span class="line">def split(n):  #求前几位和末位</span><br><span class="line">    return n // 10, n % 10  </span><br><span class="line">  </span><br><span class="line">def sum_digits(n):  #求各位之和，在此示例中用来求*2后超过10的各位之和</span><br><span class="line">    if n &lt; 10:  </span><br><span class="line">        return n  </span><br><span class="line">    else:  </span><br><span class="line">        all_but_last, last = split(n)  </span><br><span class="line">        return sum_digits(all_but_last) + last    </span><br><span class="line">      </span><br><span class="line">def luhn_sum(n):  #乘一的返回值，交互到乘二的函数</span><br><span class="line">    if n &lt; 10:  </span><br><span class="line">        return n  </span><br><span class="line">    else:  </span><br><span class="line">        all_but_last,last = split(n)  </span><br><span class="line">        return luhn_sum_double(all_but_last) + last  </span><br><span class="line">  </span><br><span class="line">def luhn_sum_double(n):  #乘二的返回值，交互到乘一的函数</span><br><span class="line">    all_but_last,last = split(n)  </span><br><span class="line">    luhn_digit = sum_digits(2 * last)  #超过十各位相加</span><br><span class="line">    if n &lt; 10:  </span><br><span class="line">        return luhn_digit  </span><br><span class="line">    else:  </span><br><span class="line">        return luhn_sum(all_but_last) + luhn_digit</span><br><span class="line">~~~</span><br><span class="line">## *Recursion and Iteration*</span><br><span class="line">- 从迭代```while```到递归，由于迭代是一种特殊的递归形式，所以只需要找到在不同迭代步骤中始终维护和保持的状态```n```并将其作为参数 </span><br><span class="line">^afb04a</span><br><span class="line">~~~python</span><br><span class="line">def sum_digits_iter(n):  </span><br><span class="line">    digit_sum = 0  </span><br><span class="line">    while n &gt; 0:  </span><br><span class="line">        n, last = split(n)  </span><br><span class="line">        digit_sum += last  </span><br><span class="line">    return digit_sum  </span><br><span class="line">  </span><br><span class="line">def sum_digits_rec(n,digit_sum):  </span><br><span class="line">    if n == 0:  </span><br><span class="line">        return digit_sum  </span><br><span class="line">    else:  </span><br><span class="line">        n, last = split(n)  </span><br><span class="line">        return sum_digits_rec(n,digit_sum)</span><br><span class="line">~~~</span><br><span class="line">## *Order of Recursive Calls*</span><br><span class="line">- Cascade Function: (级联函数)</span><br><span class="line">  这个例子为了证明即在任何一次函数递归中，直到执行其```return```值之前，这个函数递归都不会完成（例如本例中先执行```cascade(n//10)```再```print```）；同时，任何调用都能出现在递归调用之前或者之后；最后，在完成每个递归调用时，从最后一个递归调用逐级向上返回，直到返回第一次函数调用</span><br><span class="line">~~~python</span><br><span class="line">def cascade(n):  </span><br><span class="line">    if n &lt; 10:  </span><br><span class="line">        print(n)  </span><br><span class="line">    else:  </span><br><span class="line">        print(n)  </span><br><span class="line">        cascade(n//10)  </span><br><span class="line">        print(n)  </span><br><span class="line">  </span><br><span class="line">def cascade(n):  </span><br><span class="line">    print(n)  </span><br><span class="line">    if n &gt; 10:  </span><br><span class="line">        cascade(n//10)  </span><br><span class="line">        print(n)</span><br><span class="line">~~~</span><br><span class="line">## *Example: Inverse Cascade*</span><br><span class="line">- 打印逆向级联</span><br><span class="line">~~~python</span><br><span class="line">def f_then_g(f,g,n):  </span><br><span class="line">    if n:  </span><br><span class="line">        f(n)  </span><br><span class="line">        g(n)  </span><br><span class="line">  </span><br><span class="line">def inverse_cascade(n):  </span><br><span class="line">    grow(n)  </span><br><span class="line">    print(n)  </span><br><span class="line">    shrink(n)</span><br><span class="line"></span><br><span class="line">grow = lambda n: f_then_g(grow,print,n//10)  </span><br><span class="line">shrink = lambda n: f_then_g(print,shrink,n//10)  </span><br><span class="line">~~~</span><br><span class="line"># Lecture 7: Tree Recursion（树递归）</span><br><span class="line">&lt;big&gt;树递归即指在某函数内有不止一次的函数递归调用，每个值都能转化为树状的基本结构直接返回对应的值&lt;/big&gt;</span><br><span class="line">## *Tree Recursion*</span><br><span class="line">~~~python</span><br><span class="line">def fib(n):  #计算斐波那契数列</span><br><span class="line">    if n === 0:  </span><br><span class="line">        return 0  </span><br><span class="line">    elif n == 1:  </span><br><span class="line">        return 1  </span><br><span class="line">    else:  </span><br><span class="line">        return fib(n-1) +fib(n-2)</span><br><span class="line">~~~</span><br><span class="line">&lt;small&gt;（由于计算了很多重复值导致运行速度会慢）&lt;/small&gt;</span><br><span class="line">## *Example: Paths*</span><br><span class="line">&lt;small&gt;判断从一个m行n列的表格一角走向另一个对角有多少种可能的路径&lt;/small&gt;</span><br><span class="line">- Thinking: 在每一个格子时都有向上和向右两种走法，而不管往哪个方向走一格，问题都可以转化为剩余```m-1```或```n-1```个格子所具有的路径数量</span><br><span class="line">~~~python</span><br><span class="line">def paths(m,n):</span><br><span class="line">	if m == 1 or n == 1:</span><br><span class="line">		return 1</span><br><span class="line">	else:</span><br><span class="line">		return path(m-1,n) + path(m,n-1)</span><br><span class="line">~~~</span><br><span class="line">## *Example: Knapsack*</span><br><span class="line">&lt;small&gt;判断n的各位数字组合能否等于k，可能等于返回True，反之返回False&lt;/small&gt;</span><br><span class="line">- u1s1这个是有点没看懂的，自己的理解大概是如果n有0位不影响加减所以直接返回```True```，然后```with_last```函数每次去掉最后一位后查看包含此步骤中n的最后一位能否满足条件，而```without_last```则表示不包含此步骤中的最后一位能否满足。</span><br><span class="line">  综上，这个函数主题应用树递归就是在n的每一位数都提供加上这位数字和不加上这位数字两种选择，以此来包含所有可能</span><br><span class="line">~~~python</span><br><span class="line">def knap(n,k):</span><br><span class="line">	if n == 0:</span><br><span class="line">		return k == 0</span><br><span class="line">	else:</span><br><span class="line">		with_last = knap(n // 10, k - n % 10)</span><br><span class="line">		without_last = knap(n // 10,k)</span><br><span class="line">		return with_last or without_last</span><br><span class="line">~~~</span><br><span class="line">## *Example: Counting Partitions*</span><br><span class="line">- 计数分区：即定义一个函数```count_partitions(n,m)```，求出在单一分区最大为```m```的情况下，在```n```中能有多少种分区的组合。例如```count_partitions(6,4)```即有如下要求和9种解：![](./CS61A学习笔记/Pasted%20image%2020230714145032.png)</span><br><span class="line">- Thinking：要应用树递归的基本思路，即将所有情况分成两种情况，逐渐简化为基本情况，并且简化后的情况可以用原情况表示。本例中，可以先分为分区中有4的情况和分区中最大为3的情况。而对于第一种情况而言，可以视作求2的分区，即```n-m```的可能分区情况。如此，本例转化为的递归即为```count_partitions(n-m,m)```和```count_partitions(n,m-1)```的递归数总和，代码如下</span><br><span class="line">~~~python</span><br><span class="line">def count_partitions(n,m):  </span><br><span class="line">    if m == 0:  </span><br><span class="line">        return 0  </span><br><span class="line">    elif n == 0:  </span><br><span class="line">        return 1  </span><br><span class="line">    elif n &lt; 0:  </span><br><span class="line">        return 0  </span><br><span class="line">    else:  </span><br><span class="line">        with_m = count_partitions(n-m, m)  </span><br><span class="line">        without_m = count_partitions(n, m-1)  </span><br><span class="line">        return with_m + without_m</span><br><span class="line">~~~</span><br><span class="line"></span><br><span class="line">## *Example: Binary Print*</span><br><span class="line">- [ ] （这节没听懂一点就是说）改日再会吧...</span><br><span class="line">## *Implementing Functions*</span><br><span class="line">- 这颗主要讲了一个程序填空题的解题思路吧，大概就是先理解框架，然后代入具体示例思考在每一步应该完成怎样的操作。</span><br><span class="line">~~~python</span><br><span class="line">def remove(n,digit):  #删除n中为digit的数字</span><br><span class="line">    kept, digits = 0, 0  #digits常做计数器</span><br><span class="line">    while n &gt; 0 :  </span><br><span class="line">        n, last = n // 10, n % 10  </span><br><span class="line">        if last != digit :  </span><br><span class="line">            kept = kept + last * 10 ** digits  #利用digits实现位数转换</span><br><span class="line">            digits += 1  </span><br><span class="line">    return kept</span><br><span class="line">#另一种思路</span><br><span class="line">def remove(n,digit):  </span><br><span class="line">    kept, digits = 0, 0  </span><br><span class="line">    while n &gt; 0 :  </span><br><span class="line">        n, last = n // 10, n % 10  </span><br><span class="line">        if last != digit :  </span><br><span class="line">            kept = kept / 10 + last  </span><br><span class="line">            digits += 1  </span><br><span class="line">    return round(kept * 10 ** (digits - 1))</span><br><span class="line">~~~</span><br><span class="line">## *Lab03: Recursion, Tree Recursion*</span><br><span class="line">### Q2: WWPD: Journey to the Center of the Earth</span><br><span class="line">- [ ] 这个还是有点似懂非懂，就是单纯凭理解感觉是```70km 2900km 5300km 2900km 5300km 2900km```，但是实际上好像涉及函数调用嵌套，最后还有个函数定义（？</span><br><span class="line">~~~python</span><br><span class="line">def crust():  </span><br><span class="line">    print(&quot;70km&quot;)  </span><br><span class="line">    def mantle():  </span><br><span class="line">        print(&quot;2900km&quot;)  </span><br><span class="line">        def core():  </span><br><span class="line">            print(&quot;5300km&quot;)  </span><br><span class="line">            return mantle()  </span><br><span class="line">        return core  </span><br><span class="line">    return mantle  </span><br><span class="line">  </span><br><span class="line">drill = crust  </span><br><span class="line">drill = drill()  # 70km</span><br><span class="line">drill = drill()  # 2900km</span><br><span class="line">drill = drill()  #5300km</span><br><span class="line">				 #2900km</span><br><span class="line">drill()          #5300km</span><br><span class="line">				 #2900km</span><br><span class="line">				 #Function</span><br><span class="line">~~~</span><br><span class="line">![](./CS61A学习笔记/Pasted%20image%2020230715221249.png)</span><br><span class="line">### Q4: Repeated, repeated</span><br><span class="line">- 这个算是记一下自己的解题思路吧，就是先自然用```while```循环写了，然后想办法用递归替换迭代循环吧（让我们一起高呼：这就是GPT!）</span><br><span class="line">  在递归执行中因为直接返回```repeated(f,n-1)```所以就不需要```repeated_g```来作为&quot;中转&quot;（其实是不知道怎么能在全局变量里定义```repeated_g```的初始值且让这个语句就在递归里执行一次），所以就相当于直接赋给初始值```f(x)```</span><br><span class="line">~~~python</span><br><span class="line">#迭代while版</span><br><span class="line">def compose1(f, g):  </span><br><span class="line">    &quot;&quot;&quot;&quot;Return a function h, such that h(x) = f(g(x)).&quot;&quot;&quot;  </span><br><span class="line">    def h(x):  </span><br><span class="line">        return f(g(x))  </span><br><span class="line">    return h  </span><br><span class="line">  </span><br><span class="line">def repeated(f,n):  </span><br><span class="line">    def repeated_f(x):  </span><br><span class="line">        if n == 0:  </span><br><span class="line">            return x  </span><br><span class="line">        elif n == 1:  </span><br><span class="line">            return f(x)  </span><br><span class="line">        else:  </span><br><span class="line">            i, repeated_g = 1, f  </span><br><span class="line">            while i &lt; n:  </span><br><span class="line">                repeated_g = compose1(f,repeated_g)  </span><br><span class="line">                i += 1  </span><br><span class="line">            return repeated_g(x)  </span><br><span class="line">    return repeated_f</span><br><span class="line"></span><br><span class="line">#递归版</span><br><span class="line">def repeated(f,n):  </span><br><span class="line">    def repeated_f(x):  </span><br><span class="line">        if n == 0:  </span><br><span class="line">            return x  </span><br><span class="line">        else:  </span><br><span class="line">            return repeated(f, n-1)(f(x))  </span><br><span class="line">    return repeated_f</span><br><span class="line">~~~</span><br><span class="line">### Q5: Num eights</span><br><span class="line">- 这个的抽象程度远超我想象...本来还想用就是先定义函数做出来然后再改，但最后咋也改不出来，借鉴了一下网上的: 就是我的理解是用一个```return 0```来表示所有位数都已经判断完毕并且初始化计数器为0，然后层层向上，如果该位数是8就返回值+1</span><br><span class="line">~~~python</span><br><span class="line">def num_eights(x):</span><br><span class="line">	if x == 0:</span><br><span class="line">		return 0</span><br><span class="line">	if x % 10 == 8:</span><br><span class="line">		return num_eights(x // 10) + 1</span><br><span class="line">	return num_eights(x // 10)</span><br><span class="line">~~~</span><br><span class="line">### Q6: Ping-pong</span><br><span class="line">- 这题说真的是一点思路没有，看了网上大佬的代码后也用tutor理解了好久才勉强理解，我自己的理解大概是：</span><br><span class="line">  引入一个判定正负方向的判定值```flag```初始值为1，把所求的第```n```个```pingpong```数转化为上一个```pingpong```数和上一个```flag```的和，而根据```flag(x)```函数的定义，```flag```最终不是1就是-1（如果满足被8整除或者含8的条件，```flag(x)```等于```-flag(x-1)```，即前一个增减方向的相反，这样起到了改变增减方向的作用）</span><br><span class="line">~~~python</span><br><span class="line">def pingpong(n):</span><br><span class="line">	def flag(x):  </span><br><span class="line">	    if x == 1:  </span><br><span class="line">	        return 1  </span><br><span class="line">	    if num_eights(x) or x % 8 == 0:  </span><br><span class="line">	        return -flag(x-1)  </span><br><span class="line">	    return flag(x-1)  </span><br><span class="line">	if n == 1:  </span><br><span class="line">	    return 1  </span><br><span class="line">	return pingpong(n-1) + flag(n-1)</span><br><span class="line">~~~</span><br><span class="line">## *HW03: Higher-Order Functions, Self Reference, Recursion, Tree Recursion*</span><br><span class="line">### Q1: Compose</span><br><span class="line">- [ ] 主打一个一个都不会做...我是真没办法透彻理解这个咋过来的，充其量能说服自己的一种理解是：(读题 认清```func```是所有嵌套 可能会想明白一点)</span><br><span class="line">      ```composer(func)```函数直接收了一个参数```func()```，表示已有的全部函数嵌套；最终```func_adder(g)```实际上要返回一个```func(g(x))```的新函数，并把它作为参数```func()```传回给```composer()```函数，也就是添加了一个新函数进入所有函数的嵌套；最终返回```func```（已有嵌套函数）和```func_adder```（添加新函数工具函数）</span><br><span class="line">	      对于这种两参数可以借鉴一下这个例子 [[#^afb04a]]</span><br><span class="line">~~~python</span><br><span class="line">def composer(func = lambda x: x):</span><br><span class="line">    def func_adder(g):</span><br><span class="line">        h = lambda x: func(g(x))</span><br><span class="line">        return composer(h)</span><br><span class="line">    return func, func_adder</span><br><span class="line">~~~</span><br><span class="line">### Q2: G Function</span><br><span class="line">- 哦莫，终于做出来一个，记录一下递归和迭代的不同思路</span><br><span class="line">  需要注意的就是返回分清是返回函数还是具体值（即```g_iter_f```和```g_iter_f()```的区别）</span><br><span class="line">~~~python</span><br><span class="line">def g(n):   #递归</span><br><span class="line">	if n &lt;= 3:  </span><br><span class="line">	    return n  </span><br><span class="line">	else:  </span><br><span class="line">	    return g(n-1) + 2 * g(n-2) + 3 * g(n-3)</span><br><span class="line"></span><br><span class="line">def g_iter(n):    #迭代</span><br><span class="line">	def g_iter_f():  </span><br><span class="line">	    if n &lt;= 3:  </span><br><span class="line">	        return n  </span><br><span class="line">	    else:  </span><br><span class="line">	        i, loc = 1, 0  </span><br><span class="line">	        while i &lt;= 3:  </span><br><span class="line">	            loc += i * g(n - i)  </span><br><span class="line">	            i += 1  </span><br><span class="line">	        return loc  </span><br><span class="line">	return g_iter_f()</span><br><span class="line">~~~</span><br><span class="line">### Q3: Missing Digits</span><br><span class="line">- 感觉很有必要先来记录以下这个在面对跟数字位数有关的问题是```all_but_last = n // 10```和```last = n % 10```的思路（每次看到恍然大悟自己想都想不到这个点）</span><br><span class="line">- 先读题读明白，```missing_digits(n)```提取的参数本身就是一个各位数字逐渐增大的参数，所以思路是从最后一位```last```和前一位```last_last```比较，如果相差小于等于1说明这两位数字之间没缺失，大于1说明缺失了```last - last_last - 1```个数字，然后用递归继续判定前```all_but_last```位数字；注意在```return```值中可以加上每次缺失的数字个数，这种返回方式可以类比一下这个[[#^756591]]</span><br><span class="line">	  还有就是别忘了基本条件```basic case```，否则会一直递归（报错```RecursionError: maximum recursion depth exceeded in comparison```)</span><br><span class="line">~~~python</span><br><span class="line">def missing_digits(n):</span><br><span class="line">	all_but_last, last = n // 10, n % 10  </span><br><span class="line">	if all_but_last == 0:  </span><br><span class="line">	    return 0  </span><br><span class="line">	last_last = all_but_last % 10  </span><br><span class="line">	if last - last_last &lt;= 1:  </span><br><span class="line">	    miss = 0  </span><br><span class="line">	else:  </span><br><span class="line">	    miss = last - last_last - 1  </span><br><span class="line">	return missing_digits(all_but_last) + miss</span><br><span class="line">~~~</span><br><span class="line">### Q4: Count Change</span><br><span class="line">- 类比类比and类比！这个整体思路就是应用上面计数分区[[#*Example Counting Partitions*]]的思路，分先用含最大的和不含最大的m进行分类</span><br><span class="line">	  过程中遇到了一点小问题，就是在不应用```while```循环的情况下怎么求出小于```total```的最大m（也就是2的n次幂），求助了一下chatGPT老师给出的解决方案是转化为位运算（因为2的幂总是在二进制表示中只有一位是1，其他位都是0）。例如：7的二进制是111，共3位；所以将1向左移动2位得到100，转换为十进制就是4，是小于7最大的2的n次幂</span><br><span class="line">~~~python</span><br><span class="line">def count_change(total):  </span><br><span class="line">    def find_largest_power_of_two(x):  </span><br><span class="line">        # 将total转换为二进制字符串并得到其长度  </span><br><span class="line">        binary_length = len(bin(x)) - 2  </span><br><span class="line">        # 将1左移(binary_length - 1)位得到结果  </span><br><span class="line">        n = 1 &lt;&lt; (binary_length - 1)  </span><br><span class="line">        return n  </span><br><span class="line">    m = find_largest_power_of_two(total)  </span><br><span class="line">    def count_change_f(total, m):  </span><br><span class="line">        if m == 1:  </span><br><span class="line">            return 1  </span><br><span class="line">        elif total &lt; 0:  </span><br><span class="line">            return 0  </span><br><span class="line">        else:  </span><br><span class="line">            with_m = count_change_f(total - m, m)  </span><br><span class="line">            without_m = count_change_f(total, m // 2)  </span><br><span class="line">            return with_m + without_m  </span><br><span class="line">    return count_change_f(total, m)</span><br><span class="line">~~~</span><br><span class="line">### Q5: Towers of Hanoi</span><br><span class="line">- 过年咯！感觉还是类比计数分区那个思路[[#*Example Counting Partitions*]]好吧，太有用了！这回变成```all_but_bottom```和```bottom```了，借助```print_move```函数来打印步骤，把每一个递归都理解成两个的思路，即```all_but_bottom: start-&gt;middle bottom: start-&gt;end all_but_bottom: middle-&gt;end```就搞定！</span><br><span class="line">	  中间就怎么定义这个```middle```又去寻求一下老师帮助，方法类似于定义数组，定义了一个包含所有可能数值的集合```all_numbers```，然后使用集合的差集操作```all_numbers - &#123;start, end&#125;```来找到除了```start```和```end```之外的那个元素。由于集合是无序的，我们可以使用``pop()``方法随机获取其中的一个元素，这样```middle```就会等于剩下的那个值。</span><br><span class="line">	  虽然但是最后觉得自己像个傻子因为发现了：```middle = 6 - start - end```...</span><br><span class="line">~~~python</span><br><span class="line">def print_move(origin,destination):  </span><br><span class="line">    print(&quot;Move the top disk from rod&quot;, origin, &quot;to rod&quot;, destination)  </span><br><span class="line">  </span><br><span class="line">def move_stack(n, start, end):  </span><br><span class="line">    assert 1 &lt;= start &lt;= 3 and 1 &lt;= end &lt;= 3 and start != end, &quot;Bad start/end&quot;  </span><br><span class="line">  </span><br><span class="line">    def find_middle(start, end):  </span><br><span class="line">        all_numbers = &#123;1, 2, 3&#125;  </span><br><span class="line">        x = (all_numbers - &#123;start, end&#125;).pop()  </span><br><span class="line">        return x  </span><br><span class="line">  </span><br><span class="line">    middle = find_middle(start, end)  </span><br><span class="line">  </span><br><span class="line">    if n == 1:  </span><br><span class="line">        return print_move(start, end)  </span><br><span class="line">    else:  </span><br><span class="line">        all_but_bottom = move_stack(n-1, start, middle)  </span><br><span class="line">        bottom = move_stack(1, start, end)  </span><br><span class="line">        all_but_bottom = move_stack(n-1, middle, end)</span><br><span class="line">~~~</span><br><span class="line">### Q6: Anonymous factorial</span><br><span class="line">- OK一朝回到解放前，又一道抽象题目...直接引用一下网上博主的解释</span><br><span class="line">	  这道题要点，把函数当做参数传入，构造call, 在call里用lambda构造这个函数的behavior，这样就解决了迭代时需要函数名的问题。主要分为两部分: </span><br><span class="line">	  1. 第一个括号： (lambda f: lambda k: f(f, k)) </span><br><span class="line">	  构造一个需要f函数作为参数的函数，返回值是需要k为参数的函数，返回f函数的值，并且规定了f是一个需要2个参数的函数，f自身和k </span><br><span class="line">	  2. 第二个括号：(lambda f , k: k if k == 1 else k * f(f, k-1) ) </span><br><span class="line">	  这部分作为第一个括号的第一个call，构造f函数的行为，需要2个参数：f, k. 返回值为k或else后的值，if给出最简式，else给出，k和k-1的关系  </span><br><span class="line">	  3. 注意环境变量的变化，写成相同的名字便于理解，实际并不相同。</span><br><span class="line">~~~python</span><br><span class="line">def make_anonymous_factorial():  </span><br><span class="line">	return (lambda f: lambda n: f(f,n))(lambda f, n: n if n == 1 else n * f(f, n-1))</span><br><span class="line">~~~</span><br><span class="line"># Lecture 8: Sequences &amp; Data Abstraction（序列与数据抽象）</span><br><span class="line">## *Lists*</span><br><span class="line">- 整体感觉就是C的数组，大括号```&#123;1，2，3，4&#125;```变成中括号```[1,2,3,4]```，另外还有些小tips和示例：</span><br><span class="line">  ~~~python</span><br><span class="line">  digits = [1, 2, 3, 4]</span><br><span class="line">  len(digits) = 4  #判断数组长度</span><br><span class="line"></span><br><span class="line">  from operater import getitem</span><br><span class="line">  digits[3] &lt;--&gt; getitem(digits, 3)   #提取列表中第三个数</span><br><span class="line">  </span><br><span class="line">  &gt;&gt;&gt; [2, 7] + digits * 2  &lt;--&gt; add([2, 7], mul(digits, 2))</span><br><span class="line">  [2, 7, 1, 2, 3, 4, 1, 2, 3, 4]</span><br><span class="line">  </span><br><span class="line">  &gt;&gt;&gt; pairs = [[10, 20], [30, 40]]</span><br><span class="line">  &gt;&gt;&gt; pairs[1]</span><br><span class="line">  [30, 40]</span><br><span class="line">  &gt;&gt;&gt; pairs[1][0]</span><br><span class="line">  30</span><br><span class="line">  ~~~</span><br><span class="line">## *For Statements*</span><br><span class="line">- ```for```循环和```while```循环的用法功能对比：</span><br><span class="line">~~~python</span><br><span class="line">  def count(s, value):  </span><br><span class="line">    total, index = 0, 0   #需要定义追踪变量index</span><br><span class="line">    while index &lt; len(s):  </span><br><span class="line">        element = s[index]  </span><br><span class="line">        if element == value:  </span><br><span class="line">            total += 1  </span><br><span class="line">        index += 1  </span><br><span class="line">    return total  </span><br><span class="line">  </span><br><span class="line">def count(s, value):  </span><br><span class="line">    total = 0  </span><br><span class="line">    for element in s:     #不需要定义追踪变量，element初始化即为0且自增</span><br><span class="line">        if element == value:  </span><br><span class="line">            total += 1  </span><br><span class="line">    return total</span><br><span class="line"></span><br><span class="line">&gt;&gt;&gt; pairs = [[1, 2], [2, 2], [3, 2], [4, 4]]</span><br><span class="line">&gt;&gt;&gt; same_count = 0</span><br><span class="line">&gt;&gt;&gt; for x, y in pairs:    #固定长度序列中每个元素的名称</span><br><span class="line">...     if x == y:</span><br><span class="line">...			same_count += 1</span><br><span class="line"></span><br><span class="line">&gt;&gt;&gt; same_count</span><br><span class="line">2</span><br><span class="line">~~~</span><br><span class="line">- `for ... in ...`循环用法解释：</span><br><span class="line"></span><br><span class="line">~~~python</span><br><span class="line">&#x27;&#x27;&#x27;</span><br><span class="line">in表达式从（字符串、序列等）中依次取值，又称为遍历</span><br><span class="line">for-in遍历的对象必须是可迭代对象</span><br><span class="line">&#x27;&#x27;&#x27;</span><br><span class="line"> </span><br><span class="line">&#x27;&#x27;&#x27;</span><br><span class="line">for-in的语法结构</span><br><span class="line">for 自定义变量 in 可迭代对象:</span><br><span class="line">    循环体</span><br><span class="line">&#x27;&#x27;&#x27;</span><br><span class="line"> </span><br><span class="line"># 字符串中取值</span><br><span class="line">for item in &#x27;python&#x27;:</span><br><span class="line">	print(item)</span><br><span class="line"> </span><br><span class="line"># range产生一个整数序列，也是一个可迭代对象</span><br><span class="line">for i in range(10):</span><br><span class="line">	print(i)</span><br><span class="line"></span><br><span class="line"># 如果在循环体中不需要用到自定义变量，可将自定义变量写为‘_’</span><br><span class="line">for _ in range(5):</span><br><span class="line">	print(&#x27;人生苦短，我用python&#x27;)</span><br><span class="line">~~~</span><br><span class="line">## *Ranges*</span><br><span class="line">~~~python</span><br><span class="line">&gt;&gt;&gt; list[range(-2, 2)]</span><br><span class="line">list[range(-2, 2)]</span><br><span class="line">&gt;&gt;&gt; list(range(-2, 2))</span><br><span class="line">[-2, -1, 0, 1]</span><br><span class="line"></span><br><span class="line">&gt;&gt;&gt; list[range(4)]</span><br><span class="line">list[range(0, 4)]</span><br><span class="line">&gt;&gt;&gt; list(range(4))</span><br><span class="line">[0, 1, 2, 3]</span><br><span class="line"></span><br><span class="line">def cheer():</span><br><span class="line">	for _ in range(3):  #无用用空格或者下划线代替</span><br><span class="line">		print(&#x27;Go bears!&#x27;)</span><br><span class="line">&gt;&gt;&gt; cheer()</span><br><span class="line">Go bears!</span><br><span class="line">Go bears!</span><br><span class="line">Go bears!</span><br><span class="line">~~~</span><br><span class="line">## *List Comprehensions*</span><br><span class="line">~~~python</span><br><span class="line">odds = [1, 3, 5, 7, 9]</span><br><span class="line">&gt;&gt;&gt; [x+1 for x in odds]</span><br><span class="line">[2, 4, 6, 8, 10]</span><br><span class="line">&gt;&gt;&gt; [x for x in odds if 25 % x == 0]</span><br><span class="line">[1, 5]</span><br><span class="line"></span><br><span class="line">def divisors(n):</span><br><span class="line">    &quot;&quot;&quot;Return the integers that evenly divide n.</span><br><span class="line"></span><br><span class="line">    &gt;&gt;&gt; divisors(1)</span><br><span class="line">    [1]</span><br><span class="line">    &gt;&gt;&gt; divisors(4)</span><br><span class="line">    [1, 2]</span><br><span class="line">    &gt;&gt;&gt; divisors(12)</span><br><span class="line">    [1, 2, 3, 4, 6]</span><br><span class="line">    &gt;&gt;&gt; [n for n in range(1, 1000) if sum(divisors(n)) == n]</span><br><span class="line">    [1, 6, 28, 496]</span><br><span class="line">    &quot;&quot;&quot;</span><br><span class="line">    return [1] + [x for x in range(2, n) if n % x == 0]</span><br><span class="line">~~~</span><br><span class="line">## *Strings*</span><br><span class="line">- 对数组来说，一次只能查找一个元素；而对字符串序列来说可查找多个连续字符，如下：</span><br><span class="line">~~~python</span><br><span class="line">&gt;&gt;&gt; &#x27;here&#x27; in &quot;Where is Waldo?&quot;</span><br><span class="line">True</span><br><span class="line">&gt;&gt;&gt; 234 in [1, 2, 3, 4, 5]</span><br><span class="line">False</span><br><span class="line">&gt;&gt;&gt; [2, 3, 4] in [1, 2, 3, 4, 5]</span><br><span class="line">False</span><br><span class="line">~~~</span><br><span class="line">## *Data Abstraction*</span><br><span class="line">&lt;small&gt;Defination: A methodology by which functions enforce an abstraction barrier between representation and use&lt;/small&gt;</span><br><span class="line">- ```wishful thinking```通过保留有理数的分子分母来输出分数的准确值</span><br><span class="line">~~~python</span><br><span class="line">def mul_rational(x, y):  </span><br><span class="line">    return rational(numer(x) * numer(y), denom(x) * decom(y))  </span><br><span class="line">  </span><br><span class="line">def add_rational(x, y):  </span><br><span class="line">    nx, dx = numer(x), denom(x)  </span><br><span class="line">    ny, dy = numer(y), denom(y)  </span><br><span class="line">    return rational(nx * dy + ny * dx, dx * dy)  </span><br><span class="line">  </span><br><span class="line">def equal_rational(x, y):  </span><br><span class="line">    return numer(x) * decom(y) == numer(y) * decom(x)</span><br><span class="line">~~~</span><br><span class="line">## *Representing Rational Numbers*</span><br><span class="line">- 在定义一个列表如```pair = [1, 2]```后，可以通过解包```x, y = pair```或者运用元素运算选择符```x = pair[0]```来调用列表内容，再或者用```getitem(pair, 0)```</span><br><span class="line">~~~python</span><br><span class="line">from fractions import gcd   #Greatest common divisor  </span><br><span class="line">  </span><br><span class="line">def mul_rational(x, y):  </span><br><span class="line">    return rational(numer(x) * numer(y), denom(x) * denom(y))  </span><br><span class="line">  </span><br><span class="line">def add_rational(x, y):  </span><br><span class="line">    nx, dx = numer(x), denom(x)  </span><br><span class="line">    ny, dy = numer(y), denom(y)  </span><br><span class="line">    return rational(nx * dy + ny * dx, dx * dy)  </span><br><span class="line">  </span><br><span class="line">def equal_rational(x, y):  </span><br><span class="line">    return numer(x) * denom(y) == numer(y) * denom(x)  </span><br><span class="line">  </span><br><span class="line">def rational(n, d):  </span><br><span class="line">    &quot;&quot;&quot;Construct a rational number that represents N/D&quot;&quot;&quot;  </span><br><span class="line">    g = gcd(n, d)  </span><br><span class="line">    return [n//g, d//g]  </span><br><span class="line">  </span><br><span class="line">def numer(x):  </span><br><span class="line">    &quot;&quot;&quot;Return the numerator of rational number x.&quot;&quot;&quot;  </span><br><span class="line">    return x[0]  </span><br><span class="line">  </span><br><span class="line">def denom(x):  </span><br><span class="line">    &quot;&quot;&quot;Return the denominator of rational number x.&quot;&quot;&quot;  </span><br><span class="line">    return x[1]</span><br><span class="line">~~~</span><br><span class="line">## *Abstraction Barriers*</span><br><span class="line">- [x] 没咋看懂 放段教材（bushi</span><br><span class="line"></span><br><span class="line">哦看懂了好像...感觉就是在函数内也尽量引用高层函数，例如```square_rational```引用```mul_rational```，确定了这两个函数的对应关系，即使在更改了选择构造器签名或者更改有理数实现的情况下，因为平方(```square```)等于两原数相乘这个关系始终不变，就不需要修改这个程序</span><br><span class="line"></span><br><span class="line">在继续更多复合数据和数据抽象的示例之前，让我们考虑一下有理数示例引发的一些问题。我们根据构造函数 `rational` 和选择器函数 `numer` 和 `denom` 来定义操作。一般来说，数据抽象的基本思想是确定一组基本操作，根据这些操作可以表达对某种值的所有操作，然后仅使用这些操作来操作数据。通过以这种方式限制操作的使用，在不改变程序行为的情况下改变抽象数据的表示会容易得多。</span><br><span class="line"></span><br><span class="line">对于有理数，程序的不同部分使用不同的操作来处理有理数，如此表中所述。</span><br><span class="line"></span><br><span class="line">|该程序的一部分...|把有理数当作...|仅使用...|</span><br><span class="line">|---|---|---|</span><br><span class="line">|使用有理数进行计算|整个数据值|`add_rational, mul_rational, rationals_are_equal, print_rational`|</span><br><span class="line">|创建有理数或操作有理数|分子和分母|`rational, numer, denom`|</span><br><span class="line">|为有理数实现选择器和构造器|二元列表|列表字面量和元素选择|</span><br><span class="line"></span><br><span class="line">在上面的每一层中，最后一列中的函数强制实施抽象障碍。这些功能会由更高层次调用，并使用较低层次的抽象实现。</span><br><span class="line"></span><br><span class="line">每当程序的一部分可以使用更高级别的函数而不是使用较低级别的函数时，就会违反抽象障碍。例如，计算有理数平方的函数最好用 `mul_rational` 实现，它不对有理数的实现做任何假设。</span><br><span class="line">```python</span><br><span class="line">&gt;&gt;&gt; def square_rational(x):</span><br><span class="line">        return mul_rational(x, x)</span><br></pre></td></tr></table></figure>
直接引用分子和分母会违反一个抽象障碍。<figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br></pre></td><td class="code"><pre><span class="line"><span class="meta">&gt;&gt;&gt; </span><span class="keyword">def</span> <span class="title function_">square_rational_violating_once</span>(<span class="params">x</span>):</span><br><span class="line">        <span class="keyword">return</span> rational(numer(x) * numer(x), denom(x) * denom(x))</span><br></pre></td></tr></table></figure>
假设有理数会表示为双元素列表将违反两个抽象障碍。<figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br></pre></td><td class="code"><pre><span class="line"><span class="meta">&gt;&gt;&gt; </span><span class="keyword">def</span> <span class="title function_">square_rational_violating_twice</span>(<span class="params">x</span>):</span><br><span class="line">        <span class="keyword">return</span> [x[<span class="number">0</span>] * x[<span class="number">0</span>], x[<span class="number">1</span>] * x[<span class="number">1</span>]]</span><br></pre></td></tr></table></figure>
 抽象障碍使程序更易于维护和修改。依赖于特定表示的函数越少，想要更改该表示时所需的更改就越少。 计算有理数平方的所有这些实现都具有正确的行为，但只有第一个函数对未来的更改是健壮的。即使我们修改了有理数的表示，<code>square_rational</code> 函数也不需要更新。相比之下，当选择器函数或构造函数签名发生变化后，<code>square_rational_violating_once</code> 就需要更改，而只要有理数的实现发生变化，<code>square_rational_violating_twice</code> 就需要更新。</li>
</ol>
</li>
</ul>
<h2 id="Data-Representations"><a href="#Data-Representations" class="headerlink" title="Data Representations"></a><em>Data Representations</em></h2><p><font color="orange">维护抽象障碍的目的是为了可以更改数据表示，而不用重写整个程序</font></p>
<ul>
<li>数据抽象的关键思想在于通过数据的行为来判断数据类型，而不是通过如何构造它，以下是一个示例，展示了通过修改程序内容而不修改程序表达的一个例子：<figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br><span class="line">32</span><br><span class="line">33</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment">#在这种定义里应用列表，x作为数组列表</span></span><br><span class="line"><span class="keyword">def</span> <span class="title function_">rational</span>(<span class="params">n, d</span>):  </span><br><span class="line">    <span class="string">&quot;&quot;&quot;Construct a rational number that represents N/D&quot;&quot;&quot;</span>  </span><br><span class="line">    g = gcd(n, d)  </span><br><span class="line">    <span class="keyword">return</span> [n//g, d//g]  </span><br><span class="line">  </span><br><span class="line"><span class="keyword">def</span> <span class="title function_">numer</span>(<span class="params">x</span>):  </span><br><span class="line">    <span class="string">&quot;&quot;&quot;Return the numerator of rational number x.&quot;&quot;&quot;</span>  </span><br><span class="line">    <span class="keyword">return</span> x[<span class="number">0</span>]  </span><br><span class="line">  </span><br><span class="line"><span class="keyword">def</span> <span class="title function_">denom</span>(<span class="params">x</span>):  </span><br><span class="line">    <span class="string">&quot;&quot;&quot;Return the denominator of rational number x.&quot;&quot;&quot;</span>  </span><br><span class="line">    <span class="keyword">return</span> x[<span class="number">1</span>]</span><br><span class="line"></span><br><span class="line"><span class="comment">#在这种定义里应用高阶函数，x作为函数</span></span><br><span class="line"><span class="keyword">def</span> <span class="title function_">rational</span>(<span class="params">n, d</span>):</span><br><span class="line">	<span class="keyword">def</span> <span class="title function_">select</span>(<span class="params">name</span>):</span><br><span class="line">		<span class="keyword">if</span> name == <span class="string">&#x27;n&#x27;</span>:</span><br><span class="line">			<span class="keyword">return</span> n</span><br><span class="line">		<span class="keyword">elif</span> name == <span class="string">&#x27;d&#x27;</span>:</span><br><span class="line">			<span class="keyword">return</span> d</span><br><span class="line">	<span class="keyword">return</span> select</span><br><span class="line"></span><br><span class="line"><span class="keyword">def</span> <span class="title function_">numer</span>(<span class="params">x</span>):   <span class="comment">#这里x作为一个接收有理数（即rational函数）的函数参数</span></span><br><span class="line">	<span class="keyword">return</span> x(<span class="string">&#x27;n&#x27;</span>)</span><br><span class="line"></span><br><span class="line"><span class="keyword">def</span> <span class="title function_">denom</span>(<span class="params">x</span>):</span><br><span class="line">	<span class="keyword">return</span> x(<span class="string">&#x27;d&#x27;</span>)</span><br><span class="line"></span><br><span class="line"><span class="comment">#结果都是如下</span></span><br><span class="line"><span class="meta">&gt;&gt;&gt; </span>x, y = rational(<span class="number">1</span>, <span class="number">2</span>), rational(<span class="number">3</span>, <span class="number">8</span>)</span><br><span class="line"><span class="meta">&gt;&gt;&gt; </span>print_rational(mul_rational(x, y))</span><br><span class="line"><span class="number">3</span> / <span class="number">16</span></span><br></pre></td></tr></table></figure></li>
<li>对于第二种定义方式可以这样理解：<figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br></pre></td><td class="code"><pre><span class="line">  x = rational(<span class="number">3</span>, <span class="number">8</span>)</span><br><span class="line">  numer(x)</span><br><span class="line"><span class="comment">#对于numer函数相当于：</span></span><br><span class="line">  <span class="keyword">return</span> rational(<span class="string">&#x27;n&#x27;</span>)  <span class="comment">#即返回3</span></span><br></pre></td></tr></table></figure></li>
</ul>
<h2 id="61A-Fall-Lecture12-Video-6-Dictionary"><a href="#61A-Fall-Lecture12-Video-6-Dictionary" class="headerlink" title="61A Fall Lecture12 Video 6(Dictionary)"></a><em>61A Fall Lecture12 Video 6(Dictionary)</em></h2><ul>
<li>Dictionary: 把键位<code>key</code>和值<code>value</code>联系起来，没有顺序，例如：<figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br></pre></td><td class="code"><pre><span class="line"><span class="meta">&gt;&gt;&gt; </span>numerals = &#123;<span class="string">&#x27;I&#x27;</span>: <span class="number">1</span>, <span class="string">&#x27;V&#x27;</span>: <span class="number">5</span>, <span class="string">&#x27;X&#x27;</span>: <span class="number">10</span>&#125;</span><br><span class="line"><span class="meta">&gt;&gt;&gt; </span>numerals</span><br><span class="line">&#123;<span class="string">&#x27;I&#x27;</span>: <span class="number">1</span>, <span class="string">&#x27;V&#x27;</span>: <span class="number">5</span>, <span class="string">&#x27;X&#x27;</span>: <span class="number">10</span>&#125;  <span class="comment">#这个换不换顺序都有可能，但都无所谓</span></span><br><span class="line"><span class="meta">&gt;&gt;&gt; </span>numerals[<span class="string">&#x27;X&#x27;</span>] <span class="comment"># &#123;dictionary&#125;[&#x27;Key&#x27;]用来在dictionary中搜索</span></span><br><span class="line"><span class="number">10</span></span><br></pre></td></tr></table></figure></li>
<li>其中有键位<code>keys</code>，值<code>values</code>，和项目<code>items</code>三个变量，如下调用：<figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br></pre></td><td class="code"><pre><span class="line"><span class="meta">&gt;&gt;&gt; </span>numerals.keys()</span><br><span class="line">dict_keys([<span class="string">&#x27;I&#x27;</span>, <span class="string">&#x27;V&#x27;</span>, <span class="string">&#x27;X&#x27;</span>])</span><br><span class="line"><span class="meta">&gt;&gt;&gt; </span>numerals.values()</span><br><span class="line">dict_values([<span class="number">1</span>, <span class="number">5</span>, <span class="number">10</span>])</span><br><span class="line"><span class="meta">&gt;&gt;&gt; </span>numerals.items()</span><br><span class="line">dict_items([(<span class="string">&#x27;I&#x27;</span>, <span class="number">1</span>), (<span class="string">&#x27;V&#x27;</span>, <span class="number">5</span>), (<span class="string">&#x27;X&#x27;</span>, <span class="number">10</span>)])</span><br><span class="line"><span class="comment">#如果不调用具体值则会类似显示函数地址或者结构变量，具体如下：</span></span><br><span class="line"><span class="meta">&gt;&gt;&gt; </span>numerals.keys</span><br><span class="line">&lt;built-<span class="keyword">in</span> method keys of <span class="built_in">dict</span> <span class="built_in">object</span> at <span class="number">0x0000014567D5FFC0</span>&gt;</span><br></pre></td></tr></table></figure></li>
<li>还可以应用<code>dict</code>构造函数来创建一个<code>dictionary</code>，例如：<figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br></pre></td><td class="code"><pre><span class="line"><span class="meta">&gt;&gt;&gt; </span>items = [(<span class="string">&#x27;I&#x27;</span>, <span class="number">1</span>), (<span class="string">&#x27;V&#x27;</span>, <span class="number">5</span>), (<span class="string">&#x27;X&#x27;</span>, <span class="number">10</span>)]</span><br><span class="line"><span class="meta">&gt;&gt;&gt; </span>items</span><br><span class="line">[(<span class="string">&#x27;I&#x27;</span>, <span class="number">1</span>), (<span class="string">&#x27;V&#x27;</span>, <span class="number">5</span>), (<span class="string">&#x27;X&#x27;</span>, <span class="number">10</span>)]</span><br><span class="line"><span class="meta">&gt;&gt;&gt; </span><span class="built_in">dict</span>(items)</span><br><span class="line">&#123;<span class="string">&#x27;I&#x27;</span>: <span class="number">1</span>, <span class="string">&#x27;V&#x27;</span>: <span class="number">5</span>, <span class="string">&#x27;X&#x27;</span>: <span class="number">10</span>&#125;</span><br><span class="line"><span class="meta">&gt;&gt;&gt; </span><span class="built_in">dict</span>(items)[<span class="string">&#x27;X&#x27;</span>]</span><br><span class="line"><span class="number">10</span></span><br></pre></td></tr></table></figure></li>
<li>可以判定一个<code>key</code>是否在<code>dictionary</code>中，应用语句<code>&#39;X in numerals</code>，系统返回<code>True</code>或者<code>False</code>；与此同时，如果不确定一个<code>key</code>是否在<code>dictionary</code>中，可以应用<code>numerals.get(key, 默认值)</code>函数，赋给想判断的<code>key</code>一个默认值，如果在<code>dictionary</code>中则返回<code>dictionary</code>中对应的值，如果不在<code>dictionary</code>中则返回<code>get</code>函数中所赋的默认值</li>
<li><big>一些特殊的以及一些限制</big><ul>
<li>可以有如下定义：<figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br></pre></td><td class="code"><pre><span class="line"><span class="meta">&gt;&gt;&gt; </span>squares = &#123;x: x * x <span class="keyword">for</span> x <span class="keyword">in</span> <span class="built_in">range</span>(<span class="number">10</span>)&#125;</span><br><span class="line"><span class="meta">&gt;&gt;&gt; </span>squares</span><br><span class="line">&#123;<span class="number">0</span>: <span class="number">0</span>, <span class="number">1</span>: <span class="number">1</span>, <span class="number">2</span>: <span class="number">4</span>, <span class="number">3</span>: <span class="number">9</span>, <span class="number">4</span>: <span class="number">16</span>, <span class="number">5</span>: <span class="number">25</span>, <span class="number">6</span>: <span class="number">36</span>, <span class="number">7</span>: <span class="number">49</span>, <span class="number">8</span>: <span class="number">64</span>, <span class="number">9</span>: <span class="number">81</span>&#125;</span><br><span class="line"><span class="meta">&gt;&gt;&gt; </span>squares[<span class="number">7</span>]</span><br><span class="line"><span class="number">49</span></span><br></pre></td></tr></table></figure>
<ul>
<li>一个<code>key</code>只能对应一个值<code>value</code>，这个值不局限于数字，也可以是列表等，但是<code>key</code>不能是列表<code>list</code>、目录<code>dictionary</code>或者任何可变的类型</li>
</ul>
</li>
</ul>
</li>
</ul>
<h2 id="Examples-Lists-List-Functions"><a href="#Examples-Lists-List-Functions" class="headerlink" title="Examples: Lists(List Functions)"></a><em>Examples: Lists(List Functions)</em></h2><ul>
<li><p>这节东西好多好多，包含了很多就是列表<code>list</code>改变的函数<br><small>首先要记住的一个小tips</small>:<br>切片<code>slice [a, b]</code>包含第a个元素但不包含第b个元素，<code>[a:]</code>同理包含a</p>
</li>
<li><p><input checked disabled type="checkbox"> 
我先截几张图，之后把这个做个列表在shell里试一下（好多…好烦…）</p>
</li>
<li><p>关于<code>slice notation</code>的一些解释：<br>总结下来，<code>a[-1]</code>表示列表的最后一个值，<code>a[:-1]</code>表示列表除最后一个值以外的所有元素，<code>a[::-1]</code>表示从倒着输出列表元素</p>
<figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br><span class="line">32</span><br><span class="line">33</span><br><span class="line">34</span><br><span class="line">35</span><br><span class="line">36</span><br><span class="line">37</span><br><span class="line">38</span><br><span class="line">39</span><br><span class="line">40</span><br><span class="line">41</span><br><span class="line">42</span><br><span class="line">43</span><br><span class="line">44</span><br><span class="line">45</span><br><span class="line">46</span><br><span class="line">47</span><br></pre></td><td class="code"><pre><span class="line"><span class="meta">&gt;&gt;&gt; </span>a = [<span class="string">&#x27;a&#x27;</span>,<span class="string">&#x27;b&#x27;</span>,<span class="string">&#x27;c&#x27;</span>,<span class="string">&#x27;d&#x27;</span>,<span class="string">&#x27;e&#x27;</span>,<span class="string">&#x27;f&#x27;</span>,<span class="string">&#x27;g&#x27;</span>,<span class="string">&#x27;h&#x27;</span>,<span class="string">&#x27;g&#x27;</span>,<span class="string">&#x27;k&#x27;</span>,<span class="string">&#x27;l&#x27;</span>,<span class="string">&#x27;m&#x27;</span>]</span><br><span class="line"></span><br><span class="line"><span class="meta">&gt;&gt;&gt; </span>b = a[:] <span class="comment"># 列表切片，表示把列表a[]的值全部正序复制到列表b[]中</span></span><br><span class="line"><span class="meta">&gt;&gt;&gt; </span><span class="built_in">print</span>(b)</span><br><span class="line">[<span class="string">&#x27;a&#x27;</span>, <span class="string">&#x27;b&#x27;</span>, <span class="string">&#x27;c&#x27;</span>, <span class="string">&#x27;d&#x27;</span>, <span class="string">&#x27;e&#x27;</span>, <span class="string">&#x27;f&#x27;</span>, <span class="string">&#x27;g&#x27;</span>, <span class="string">&#x27;h&#x27;</span>, <span class="string">&#x27;g&#x27;</span>, <span class="string">&#x27;k&#x27;</span>, <span class="string">&#x27;l&#x27;</span>, <span class="string">&#x27;m&#x27;</span>]</span><br><span class="line"></span><br><span class="line"><span class="comment"># b = a[n:m]表示列表切片，复制列表a[n]到a[m-1]的内容到新的列表对象b[]</span></span><br><span class="line"><span class="comment"># 当n缺省时，默认为0，即a[:m]</span></span><br><span class="line"><span class="comment"># 当m缺省时，默认到最后，即a[n:]</span></span><br><span class="line"><span class="meta">&gt;&gt;&gt; </span>b1 = a[<span class="number">1</span>:<span class="number">4</span>]</span><br><span class="line"><span class="meta">&gt;&gt;&gt; </span><span class="built_in">print</span>(b1)</span><br><span class="line">[<span class="string">&#x27;b&#x27;</span>, <span class="string">&#x27;c&#x27;</span>, <span class="string">&#x27;d&#x27;</span>]</span><br><span class="line"></span><br><span class="line"><span class="meta">&gt;&gt;&gt; </span>b2 = a[:<span class="number">3</span>]</span><br><span class="line"><span class="meta">&gt;&gt;&gt; </span><span class="built_in">print</span>(b2)</span><br><span class="line">[<span class="string">&#x27;a&#x27;</span>, <span class="string">&#x27;b&#x27;</span>, <span class="string">&#x27;c&#x27;</span>]</span><br><span class="line"></span><br><span class="line"><span class="meta">&gt;&gt;&gt; </span>b3 = a[<span class="number">1</span>:] <span class="comment">#表示除第一个元素（编号为0）以后的全部元素</span></span><br><span class="line"><span class="meta">&gt;&gt;&gt; </span><span class="built_in">print</span>(b3)</span><br><span class="line">[<span class="string">&#x27;b&#x27;</span>, <span class="string">&#x27;c&#x27;</span>, <span class="string">&#x27;d&#x27;</span>, <span class="string">&#x27;e&#x27;</span>, <span class="string">&#x27;f&#x27;</span>, <span class="string">&#x27;g&#x27;</span>, <span class="string">&#x27;h&#x27;</span>, <span class="string">&#x27;g&#x27;</span>, <span class="string">&#x27;k&#x27;</span>, <span class="string">&#x27;l&#x27;</span>, <span class="string">&#x27;m&#x27;</span>]</span><br><span class="line"></span><br><span class="line"><span class="comment"># b = a[i:j:s]这种格式呢，i,j与上面的一样，但s表示步进，缺省为1，s可以取任何数字.</span></span><br><span class="line"><span class="comment"># 所以a[i:j:1]相当于a[i:j]</span></span><br><span class="line"></span><br><span class="line"><span class="meta">&gt;&gt;&gt; </span>b4 = a[<span class="number">1</span>:<span class="number">5</span>:<span class="number">2</span>]</span><br><span class="line"><span class="meta">&gt;&gt;&gt; </span><span class="built_in">print</span>(b4)</span><br><span class="line">[<span class="string">&#x27;b&#x27;</span>, <span class="string">&#x27;d&#x27;</span>]</span><br><span class="line"></span><br><span class="line"><span class="meta">&gt;&gt;&gt; </span>b5 = a[:<span class="number">5</span>:-<span class="number">1</span>]  <span class="comment"># 从末尾倒数取值</span></span><br><span class="line"><span class="meta">&gt;&gt;&gt; </span><span class="built_in">print</span>(b5)</span><br><span class="line">[<span class="string">&#x27;m&#x27;</span>, <span class="string">&#x27;l&#x27;</span>, <span class="string">&#x27;k&#x27;</span>, <span class="string">&#x27;g&#x27;</span>, <span class="string">&#x27;h&#x27;</span>, <span class="string">&#x27;g&#x27;</span>]</span><br><span class="line"></span><br><span class="line"><span class="meta">&gt;&gt;&gt; </span>b6 = a[<span class="number">5</span>::-<span class="number">2</span>]</span><br><span class="line"><span class="meta">&gt;&gt;&gt; </span><span class="built_in">print</span>(b6)  <span class="comment"># 从a[n]处倒数取值</span></span><br><span class="line">[<span class="string">&#x27;f&#x27;</span>, <span class="string">&#x27;d&#x27;</span>, <span class="string">&#x27;b&#x27;</span>]</span><br><span class="line"></span><br><span class="line"><span class="meta">&gt;&gt;&gt; </span>b7 = a[::-<span class="number">1</span>]  <span class="comment"># 倒着取值</span></span><br><span class="line"><span class="meta">&gt;&gt;&gt; </span><span class="built_in">print</span>(b7)</span><br><span class="line">[<span class="string">&#x27;m&#x27;</span>, <span class="string">&#x27;l&#x27;</span>, <span class="string">&#x27;k&#x27;</span>, <span class="string">&#x27;g&#x27;</span>, <span class="string">&#x27;h&#x27;</span>, <span class="string">&#x27;g&#x27;</span>, <span class="string">&#x27;f&#x27;</span>, <span class="string">&#x27;e&#x27;</span>, <span class="string">&#x27;d&#x27;</span>, <span class="string">&#x27;c&#x27;</span>, <span class="string">&#x27;b&#x27;</span>, <span class="string">&#x27;a&#x27;</span>]</span><br><span class="line"></span><br><span class="line"><span class="meta">&gt;&gt;&gt; </span>b8 = a[-<span class="number">1</span>]   <span class="comment">#最后一个值</span></span><br><span class="line"><span class="meta">&gt;&gt;&gt; </span><span class="built_in">print</span>(b8)</span><br><span class="line"><span class="string">&#x27;m&#x27;</span></span><br><span class="line"></span><br><span class="line"><span class="meta">&gt;&gt;&gt; </span>b9 = a[:-<span class="number">1</span>]   <span class="comment">#除最后一个值以外的元素</span></span><br><span class="line"><span class="meta">&gt;&gt;&gt; </span><span class="built_in">print</span>(b9)</span><br><span class="line">[<span class="string">&#x27;a&#x27;</span>, <span class="string">&#x27;b&#x27;</span>, <span class="string">&#x27;c&#x27;</span>, <span class="string">&#x27;d&#x27;</span>, <span class="string">&#x27;e&#x27;</span>, <span class="string">&#x27;f&#x27;</span>, <span class="string">&#x27;g&#x27;</span>, <span class="string">&#x27;h&#x27;</span>, <span class="string">&#x27;g&#x27;</span>, <span class="string">&#x27;k&#x27;</span>, <span class="string">&#x27;l&#x27;</span>]</span><br></pre></td></tr></table></figure></li>
</ul>
<p> <strong>以下表格所有条件均为：<code>s = [2, 3]</code>  <code>t = [5, 6]</code></strong></p>
<table>
<thead>
<tr>
<th>Operation(指令释义)</th>
<th>Example(示例操作)</th>
<th>Result(所得结果)</th>
</tr>
</thead>
<tbody><tr>
<td><div style="width: 180pt"><em><strong>append</strong></em>: adds one element to a list<br>NOTES: 首先注意和extend的区别：是增加一个元素，即是把t作为列表加到s；如果t作为列表被函数调用，那么对t中元素的更改会影响调用t的s</div></td>
<td><code>s.append(t)</code><br><code>t = 0</code></td>
<td><code>s = [2, 3, [5, 6]]</code><br><code>t = 0</code></td>
</tr>
<tr>
<td><div style="width: 190pt"><em><strong>extend</strong></em>: adds all elements in one list to another list<br>NOTES: 首先注意和append的区别：是增加全部元素，即要把t里的全部元素加到s上；同样的t之后的改变也不影响s</div></td>
<td><code>s.extend(t)</code><br><code>t[1] = 0</code></td>
<td><code>s = [2, 3, 5, 6]</code><br><code>t = [5, 0]</code></td>
</tr>
<tr>
<td><div style="width: 190pt"><em><strong>addition</strong></em> &amp; <em><strong>slicing</strong></em>: creating new lists containing existing elements<br>NOTES: 首先，类似于b &#x3D; a[1:]这种slice操作，所得首先是一个列表！！！(这个有坑在下面）；其次，用于a是将t作为列表与s相加，故对b[1][1]修改实际上是在对t中元素的修改，故既会影响a也会影响t</div></td>
<td><code>a = s + [t]</code><br><code>b = a[1:]</code><br><code>a[1] = 9</code><br><code>b[1][1] = 0</code></td>
<td><code>s = [2, 3]</code><br><code>t = [5, 0]</code><br><code>a = [2, 9, [5, 0]]</code><br><code>b = [3, [5, 0]]</code></td>
</tr>
<tr>
<td><div style="width: 180pt"><em><strong>list</strong></em> function: creating new lists containing existing elements</div></td>
<td><code>t = list(s)</code><br><code>s[1] = 0</code></td>
<td><code>s = [2, 0]</code><br><code>t = [2, 3]</code></td>
</tr>
<tr>
<td><div style="width: 180pt"><em><strong>slice assignment</strong></em>: replaces a slice with new values<br>NOTES: 理解c[a:a] &#x3D; b就是把b变成c的第a位，其他的全部按上边的tips(含前不含后)考虑</div></td>
<td><code>s[0: 0] = t</code><br><code>s[3:] = t</code><br><code>t[1] = 0</code></td>
<td><code>s = [5, 6, 2, 5, 6]</code><br><code>t = [5, 0]</code></td>
</tr>
<tr>
<td><div style="width: 190pt"><em><strong>pop</strong></em>: removes &amp; returns the last element<br>NOTES: 既移除s的最后一位元素，同时将元素赋给t（注意是元素不是列表）</div></td>
<td><code>t = s.pop()</code></td>
<td><code>s = [2]</code><br><code>t = 3</code></td>
</tr>
<tr>
<td><div style="width: 180pt"><em><strong>remove</strong></em>: removes the first element equal to the argument</div></td>
<td><code>t.extend(t)</code><br><code>t.remove(5)</code></td>
<td><code>s = [2, 3]</code><br><code>t = [6, 5, 6]</code></td>
</tr>
<tr>
<td><div style="width: 180pt"><em><strong>slice assignment</strong></em>: remove elements to a list by assigning [] to a slice</div></td>
<td><code>s[:1] = []</code><br><code>t[0: 2] = []</code></td>
<td><code>s = [3]</code><br><code>t = []</code></td>
</tr>
</tbody></table>
<ul>
<li>对下面的<br><img src="/2023/11/08/CS61A%E5%AD%A6%E4%B9%A0%E7%AC%94%E8%AE%B0/Pasted%20image%2020230722005339.png"></li>
</ul>
<h2 id="Lab-4-Python-Lists-Data-Abstraction"><a href="#Lab-4-Python-Lists-Data-Abstraction" class="headerlink" title="Lab 4: Python Lists, Data Abstraction"></a><em>Lab 4: Python Lists, Data Abstraction</em></h2><h3 id="Q2-Reverse-iteratively"><a href="#Q2-Reverse-iteratively" class="headerlink" title="Q2: Reverse (iteratively)"></a>Q2: Reverse (iteratively)</h3><ul>
<li>类比一下C语言里面数组指针的特殊性</li>
<li><small>上面这个是自己写的，有个很明显的缺陷就是定义数组只有4位（这个相当于占了知道示例的便宜</small><figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">def</span> <span class="title function_">reverse_iter</span>(<span class="params">lst</span>):  </span><br><span class="line">  n, i = <span class="built_in">len</span>(lst), <span class="number">0</span></span><br><span class="line">  <span class="comment"># a = lst</span></span><br><span class="line">  <span class="comment"># 如果这里这样定义，在更改a中元素的同时lst的元素也会被更改  </span></span><br><span class="line">  a = [<span class="number">0</span>, <span class="number">0</span>, <span class="number">0</span>, <span class="number">0</span>]  </span><br><span class="line">  <span class="keyword">while</span> i &lt; n:  </span><br><span class="line">      a[i] = lst[n - i - <span class="number">1</span>]  </span><br><span class="line">      i += <span class="number">1</span>  </span><br><span class="line">  <span class="keyword">return</span> a</span><br></pre></td></tr></table></figure></li>
<li><small>之后这个是大佬的代码，借助了for循环的迭代用法和列表的加法顺序性质</small><figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">def</span> <span class="title function_">reverse_iter</span>(<span class="params">lst</span>):</span><br><span class="line">	ans = []</span><br><span class="line">	<span class="keyword">for</span> x <span class="keyword">in</span> lst:</span><br><span class="line">		ans = [x] + ans</span><br><span class="line">	<span class="keyword">return</span> ans</span><br></pre></td></tr></table></figure>
（关于<code>for-in</code>循环的用法详见[[#<em>For Statements</em>]]）</li>
</ul>
<h3 id="Q3-Reverse-recursively"><a href="#Q3-Reverse-recursively" class="headerlink" title="Q3: Reverse (recursively)"></a>Q3: Reverse (recursively)</h3><ul>
<li>具体思路请详见上一个[[#<em>Examples Lists(List Functions)</em>]]中有关<code>list[-1]</code>和<code>list[:-1]</code>的解释<br><big>把握住递归的basecase+recursion的结构</big>[[#<em>Recursive functions</em>]]<figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">def</span> <span class="title function_">reverse_recursion</span>(<span class="params">lst</span>):</span><br><span class="line">	<span class="keyword">if</span> <span class="keyword">not</span> lst:</span><br><span class="line">		<span class="keyword">return</span> []</span><br><span class="line">	<span class="keyword">return</span> [lst[-<span class="number">1</span>]] + reverse_recursion(lst[:-<span class="number">1</span>])</span><br></pre></td></tr></table></figure></li>
</ul>
<h3 id="Q5-Closer-city"><a href="#Q5-Closer-city" class="headerlink" title="Q5: Closer city"></a>Q5: Closer city</h3><ul>
<li>学一个选择返回的语句<figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">if</span> distance_a &lt; distance_b:  </span><br><span class="line">    <span class="keyword">return</span> get_name(city_a)  </span><br><span class="line"><span class="keyword">else</span>:  </span><br><span class="line">    <span class="keyword">return</span> get_name(city_b)</span><br><span class="line"><span class="comment">#等效于</span></span><br><span class="line"><span class="keyword">return</span> get_name(city_a) <span class="keyword">if</span> distance_a &lt; distance_b <span class="keyword">else</span> get_name(city_b)</span><br></pre></td></tr></table></figure></li>
</ul>
<h3 id="Q7-Add-Characters"><a href="#Q7-Add-Characters" class="headerlink" title="Q7: Add Characters"></a>Q7: Add Characters</h3><ul>
<li>就告诉自己一句话：别怕递归！按思路走[[#<em>Recursive functions</em>]]，对于字符串的基本情况记得考虑一下<code>len(list) == 0</code><figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">def</span> <span class="title function_">add_chars</span>(<span class="params">w1, w2</span>): </span><br><span class="line">    <span class="keyword">if</span> <span class="built_in">len</span>(w1) == <span class="number">0</span>:  </span><br><span class="line">        <span class="keyword">return</span> <span class="string">&quot;&quot;</span> </span><br><span class="line"><span class="comment">#OK犯病不知道为什么这里新建空字符串和返回空字符串都不行，就要我返回w1或者w2 </span></span><br><span class="line">    <span class="keyword">if</span> w1[<span class="number">0</span>] == w2[<span class="number">0</span>]:  </span><br><span class="line">        <span class="keyword">return</span> add_chars(w1[<span class="number">1</span>:], w2[<span class="number">1</span>:])  </span><br><span class="line">    <span class="keyword">return</span> w2[<span class="number">0</span>] + add_chars(w1, w2[<span class="number">1</span>:])</span><br></pre></td></tr></table></figure></li>
</ul>
<h1 id="Lecture-9-Functional-Decomposition-Debugging（功能分解与调试）"><a href="#Lecture-9-Functional-Decomposition-Debugging（功能分解与调试）" class="headerlink" title="Lecture 9: Functional Decomposition &amp; Debugging（功能分解与调试）"></a>Lecture 9: Functional Decomposition &amp; Debugging（功能分解与调试）</h1><h2 id="Assertions"><a href="#Assertions" class="headerlink" title="Assertions"></a><em>Assertions</em></h2><ul>
<li><code>assert</code>函数为断言函数，用来检查代码是否符合已有的理解。如果函数表达式的结果为真则没有任何效果产生，如果之后的表达式结果为假则返回预先设置好的报错信息，可以去看一下之前汉诺塔那个事例中用过[[#Q5 Towers of Hanoi]]</li>
<li><code>isinstance(数据, 数据类型)</code>函数则是一个判断所给数据是否为指定数据类型的函数，是则返回<code>True</code>，反之返回<code>False</code>具体的代码实现如下：<figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">def</span> <span class="title function_">fact</span>(<span class="params">x</span>):</span><br><span class="line">    <span class="keyword">assert</span> <span class="built_in">isinstance</span>(x, <span class="built_in">int</span>)</span><br><span class="line">    <span class="keyword">assert</span> x &gt;= <span class="number">0</span></span><br><span class="line">    <span class="keyword">if</span> x == <span class="number">0</span>:</span><br><span class="line">        <span class="keyword">return</span> <span class="number">1</span></span><br><span class="line">    <span class="keyword">else</span>:</span><br><span class="line">        <span class="keyword">return</span> x * fact(x-<span class="number">1</span>)</span><br><span class="line"></span><br><span class="line"><span class="keyword">def</span> <span class="title function_">half_fact</span>(<span class="params">x</span>):</span><br><span class="line">    <span class="keyword">return</span> fact(x / <span class="number">2</span>)</span><br><span class="line"></span><br><span class="line"><span class="meta">&gt;&gt;&gt; </span>half_fact(<span class="number">5</span>)</span><br><span class="line"><span class="literal">None</span>  <span class="comment">#调用fact函数时变量2.5不符合int整数类型</span></span><br></pre></td></tr></table></figure></li>
</ul>
<h2 id="Testing"><a href="#Testing" class="headerlink" title="Testing"></a><em>Testing</em></h2><ul>
<li>调试程序能够发现程序中的错误，同时让我们能够保证某一个程序小组块的正确性，进而缩小未来可能需要的调试范围，也能够记录下程序的运行过程</li>
<li>Python所提供的具体的调试方案即<code>doctest</code>函数，具体的执行方式为<code>python3 -m doctest filename.py</code>，实现测试的代码模板如下：<figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">def</span> <span class="title function_">f</span>(<span class="params">n</span>):</span><br><span class="line">	<span class="string">&quot;&quot;&quot;对函数功能的解释</span></span><br><span class="line"><span class="string">	&gt;&gt;&gt; f(1) #第一个函数验证测试示例</span></span><br><span class="line"><span class="string">	1   #第一个函数期待返回的结果值</span></span><br><span class="line"><span class="string">	&gt;&gt;&gt; f(2)</span></span><br><span class="line"><span class="string">	2</span></span><br><span class="line"><span class="string">	&quot;&quot;&quot;</span></span><br><span class="line">	<span class="comment">#...具体函数代码</span></span><br></pre></td></tr></table></figure></li>
</ul>
<h2 id="Print-Debugging"><a href="#Print-Debugging" class="headerlink" title="Print Debugging"></a><em>Print Debugging</em></h2><ul>
<li>即应用打印过程值的方式来观察代码运行步骤，以起到检测调试代码的效果<figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">def</span> <span class="title function_">fact</span>(<span class="params">x</span>):</span><br><span class="line">    <span class="comment"># assert isinstance(x, int)</span></span><br><span class="line">    <span class="comment"># assert x &gt;= 0</span></span><br><span class="line">    <span class="built_in">print</span>(<span class="string">&quot;Debug x = &quot;</span>, x)</span><br><span class="line">    <span class="keyword">if</span> x == <span class="number">0</span>:</span><br><span class="line">        <span class="keyword">return</span> <span class="number">1</span></span><br><span class="line">    <span class="keyword">else</span>:</span><br><span class="line">        <span class="keyword">return</span> x * fact(x-<span class="number">1</span>)</span><br><span class="line"></span><br><span class="line"><span class="keyword">def</span> <span class="title function_">half_fact</span>(<span class="params">x</span>):</span><br><span class="line">    <span class="keyword">return</span> fact(x / <span class="number">2</span>)</span><br><span class="line"></span><br><span class="line"><span class="meta">&gt;&gt;&gt; </span>fact(<span class="number">2</span>)</span><br><span class="line">x = <span class="number">2</span></span><br><span class="line">x = <span class="number">1</span></span><br><span class="line">x = <span class="number">0</span></span><br><span class="line"><span class="number">2</span></span><br></pre></td></tr></table></figure></li>
</ul>
<h2 id="Interative-Debugging"><a href="#Interative-Debugging" class="headerlink" title="Interative Debugging"></a><em>Interative Debugging</em></h2><ul>
<li>交互调试（Interative Debugging）再python中通常被等同于是一种叫做<code>REPL: Read-Eval-Print-Loop(读取-求值-打印-循环)</code>的工具，可以近似认为是python的命令行窗口，这种方式可以不用在PyCharm中不断的修改代码并运行，而是直接在命令行窗口中执行命令，具体指令为<code>python3 -i filename.py</code>。</li>
</ul>
<h2 id="Error-Types"><a href="#Error-Types" class="headerlink" title="Error Types"></a><em>Error Types</em></h2><ul>
<li>本节介绍一些常见的Python报错，用来判断自己的程序出现了什么问题</li>
</ul>
<ol>
<li>SyntaxError(语法错误)<ul>
<li>出现此类错误表示您运行的文件中有不是有效的Python标准语法，程序中有错误语法或者错别字等</li>
<li>应该试图搜索缺失或多余的括号、<code>if while</code>等语句末尾缺失的冒号，或是开始的声明中却没有包含内容</li>
</ul>
</li>
<li>IndentationError(缩进错误)<ul>
<li>出现此类错误表示由于缩进不一致导致语法不正确，或者是因为用错了程序文本编辑器</li>
<li>应该试图搜索一下是否出现混淆空格和Tab的情况、错位情况，或者将自己的程序在一个程序编辑器中打开，还有可能是用错了空格类型（有不止一种空格类型）</li>
</ul>
</li>
<li>TypeError: ‘X’ object is not callable…(对象类型不可调用错误)<ul>
<li><input disabled type="checkbox"> 出现此类错误表示数据X的类型不能被看作函数，在函数过程中调用了一个非函数变量</li>
<li><input disabled type="checkbox"> 应该被分配给函数的变量被分配给了非函数，或者局部变量中不包含全局变量里的同名函数</li>
</ul>
</li>
<li>TypeError: … NoneType …(类型错误)<ul>
<li>出现此类错误表示在程序不该使用的某处运用了<code>None</code></li>
<li>事实上表示函数没有返回<code>return</code>语句</li>
</ul>
</li>
<li>NameError or UnboundLocalError(命名错误&amp;非绑定本地错误)<ul>
<li>出现此类错误表示Python寻找一个变量名但没找到</li>
<li><input disabled type="checkbox"> 检查名称拼写错误，另一种不太常见的情况是在局部框架中对一个全局框架中的变量做了阴影处理（没理解，代码如下）<figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">def</span> <span class="title function_">f</span>(<span class="params">x</span>):</span><br><span class="line">	<span class="keyword">return</span> x ** <span class="number">2</span></span><br><span class="line"></span><br><span class="line"><span class="keyword">def</span> <span class="title function_">g</span>(<span class="params">x</span>):</span><br><span class="line">	y = f(x)</span><br><span class="line">	<span class="keyword">def</span> <span class="title function_">f</span>():</span><br><span class="line">		<span class="keyword">return</span> y + x</span><br><span class="line">	<span class="keyword">return</span> f</span><br></pre></td></tr></table></figure></li>
</ul>
</li>
</ol>
<h2 id="Tracebacks"><a href="#Tracebacks" class="headerlink" title="Tracebacks"></a><em>Tracebacks</em></h2><ul>
<li>程序返回的报错包括报错本身，返回错误的行数和每行都在进行着什么进程，最近的调用和错误返回将会显示在最底部</li>
<li>牢记基本的报错含义，依次浏览各行检查可能出错的位置。</li>
</ul>
<h2 id="Exceptions"><a href="#Exceptions" class="headerlink" title="Exceptions"></a><em>Exceptions</em></h2><ul>
<li>编程语言中的一种内置机制用于声明和反映异常的地方（这节没听懂）</li>
</ul>
<h2 id="Rasing-Exceptions-引发异常"><a href="#Rasing-Exceptions-引发异常" class="headerlink" title="Rasing Exceptions(引发异常)"></a><em>Rasing Exceptions(引发异常)</em></h2><ol>
<li><strong>Assert</strong>: 最简单常见的引发报错的方式便是断言语句<code>assert</code>，语法为<code>assert&lt;表达式&gt;, &lt;string&gt;</code>，例如：<code>assert False, &#39;Error&#39;</code>会返回<code>AssertionError: Error</code>. 同时由于<code>assert</code>语句会减慢程序运行速度，可以使用<code>python3 -O</code>语句来忽略程序中的所有<code>assert</code>语句（相当于屏蔽了<code>__debug__</code>语句(会返回False)</li>
<li><strong>Raise</strong>: 感官上就是引发异常并抛出一个报错，格式大概是<code>raise &lt;错误类型(如NameError, TypeError, KeyError(在dictionary中找不到对应的key), RuntimeError(超出运行时间), Exceptions等)&gt; (&#39;报错内容&#39;)</code></li>
</ol>
<h2 id="Try-Statements"><a href="#Try-Statements" class="headerlink" title="Try Statements"></a><em>Try Statements</em></h2><ul>
<li><code>try</code>语句用来处理异常，具体语法如下:<figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">try</span>:</span><br><span class="line">	&lt;<span class="keyword">try</span> suite&gt;</span><br><span class="line"><span class="keyword">except</span> &lt;出现异常类型&gt; <span class="keyword">as</span> &lt;命名&gt;:</span><br><span class="line">	&lt;<span class="keyword">except</span> suite&gt;</span><br></pre></td></tr></table></figure>
<code>try</code>语句的执行规则：</li>
</ul>
<ol>
<li>首先执行<code>&lt;try suite&gt;</code>，如果运行一切正常，就不执行异常语句<code>except suite</code>；</li>
<li>如果在执行<code>&lt;try suite&gt;</code>的过程中产生了某种异常，则执行<code>except</code>语句中对应异常类型的<code>except suite</code>语句；</li>
<li><code>try</code>语句的执行不会导致解释器停止工作，只会在特定出现异常情况下执行<code>except</code>操作<br>以下是一个示例：<figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment">#一种很常见的做法，当我们试图把一个名称绑定到一个值上但没有成功，就把名称绑定到特定值</span></span><br><span class="line"><span class="meta">&gt;&gt;&gt; </span><span class="keyword">try</span>:</span><br><span class="line"><span class="meta">... </span>	x = <span class="number">1</span> / <span class="number">0</span></span><br><span class="line"><span class="meta">... </span><span class="keyword">except</span> ZeroDivisionError <span class="keyword">as</span> e:</span><br><span class="line"><span class="meta">... </span>	<span class="built_in">print</span>(<span class="string">&#x27;handling a&#x27;</span>, <span class="built_in">type</span>(e))</span><br><span class="line"><span class="meta">... </span>    x = <span class="number">0</span></span><br><span class="line">...</span><br><span class="line">handling a &lt;<span class="keyword">class</span> <span class="string">&#x27;ZeroDivisionError&#x27;</span>&gt;</span><br><span class="line"><span class="meta">&gt;&gt;&gt; </span>x</span><br><span class="line"><span class="number">0</span></span><br></pre></td></tr></table></figure></li>
</ol>
<ul>
<li>下面这个示例是为了对比以显示出<code>try</code>语句不会使程序停止运行的特性<figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">def</span> <span class="title function_">invert</span>(<span class="params">x</span>):  </span><br><span class="line">    y = <span class="number">1</span> / x  </span><br><span class="line">    <span class="built_in">print</span>(<span class="string">&#x27;Never print if x is zero.&#x27;</span>)  </span><br><span class="line">    <span class="keyword">return</span> y  </span><br><span class="line">  </span><br><span class="line"><span class="keyword">def</span> <span class="title function_">invert_safe</span>(<span class="params">x</span>):  </span><br><span class="line">    <span class="keyword">try</span>:  </span><br><span class="line">        <span class="keyword">return</span> invert(x)  </span><br><span class="line">    <span class="keyword">except</span> ZeroDivisionError <span class="keyword">as</span> e:  </span><br><span class="line">        <span class="built_in">print</span>(<span class="string">&#x27;handled&#x27;</span>, e)  </span><br><span class="line">        <span class="keyword">return</span> <span class="number">0</span></span><br><span class="line"></span><br><span class="line"><span class="meta">&gt;&gt;&gt; </span>invert_safe(<span class="number">0</span>)</span><br><span class="line">handled division by zero <span class="comment">#这里的division by zero是原本1/0的报错</span></span><br><span class="line"><span class="number">0</span></span><br></pre></td></tr></table></figure></li>
<li>当输入指令<code>invert_safe(1/0)</code>时，程序不会运行，因为操作数<code>1/0</code>本身遍已经产生了<code>ZeroDivisionError</code>异常</li>
<li>运算符在操作数之前计算，即当<code>&gt;&gt;&gt; inverrrrt_safe(1/0)</code>时，会优先出现<code>NameError: name &#39;inverrrrt_safe&#39; is not defined</code></li>
<li>当遇到如下嵌套<code>try</code>语句时，经过内部<code>try</code>语句执行后的部分便已经变成了一个没有异常运行良好的程序，所以外层的<code>except suite</code>永远不会被执行(代码如下)<figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br></pre></td><td class="code"><pre><span class="line"><span class="meta">&gt;&gt;&gt; </span><span class="keyword">try</span>:</span><br><span class="line"><span class="meta">... </span>    invert_safe(<span class="number">0</span>)</span><br><span class="line"><span class="meta">... </span><span class="keyword">except</span> ZeroDivisionError <span class="keyword">as</span> e:</span><br><span class="line"><span class="meta">... </span>    <span class="built_in">print</span>(<span class="string">&#x27;handled!&#x27;</span>)</span><br><span class="line">...</span><br><span class="line">handled division by zero  <span class="comment">#不会执行外部循环的handled！语句</span></span><br><span class="line"><span class="number">0</span></span><br></pre></td></tr></table></figure></li>
</ul>
<h2 id="Example-Reduce"><a href="#Example-Reduce" class="headerlink" title="Example: Reduce"></a><em>Example: Reduce</em></h2><p>对<code>reduce</code>函数的解释如下：<br><img src="/2023/11/08/CS61A%E5%AD%A6%E4%B9%A0%E7%AC%94%E8%AE%B0/Pasted%20image%2020230808143852.png"></p>
<figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br><span class="line">32</span><br><span class="line">33</span><br><span class="line">34</span><br><span class="line">35</span><br><span class="line">36</span><br><span class="line">37</span><br><span class="line">38</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">from</span> operator <span class="keyword">import</span> add, mul, truediv  </span><br><span class="line">  </span><br><span class="line"><span class="keyword">def</span> <span class="title function_">divide_all</span>(<span class="params">n, ds</span>):  </span><br><span class="line">    <span class="keyword">try</span>:  </span><br><span class="line">        <span class="keyword">return</span> reduce(truediv, ds, n)  </span><br><span class="line">    <span class="keyword">except</span> ZeroDivisionError <span class="keyword">as</span> e:  </span><br><span class="line">        <span class="keyword">return</span> <span class="built_in">float</span>(<span class="string">&#x27;inf&#x27;</span>)  </span><br><span class="line">  </span><br><span class="line"><span class="keyword">def</span> <span class="title function_">reduce</span>(<span class="params">f, s, initial</span>):   <span class="comment">#循环</span></span><br><span class="line">    <span class="string">&quot;&quot;&quot;Combine elements of s using f starting with initial  </span></span><br><span class="line"><span class="string">  </span></span><br><span class="line"><span class="string">    &gt;&gt;&gt; reduce(mul, [2, 4, 8], 1)    </span></span><br><span class="line"><span class="string">    64    </span></span><br><span class="line"><span class="string">    &gt;&gt;&gt; reduce(add, [1, 2, 3, 4], 0)</span></span><br><span class="line"><span class="string">	10    </span></span><br><span class="line"><span class="string">	&quot;&quot;&quot;</span>    </span><br><span class="line">	<span class="keyword">for</span> x <span class="keyword">in</span> s:  </span><br><span class="line">        initial = f(initial, x)  </span><br><span class="line">    <span class="keyword">return</span> initial  </span><br><span class="line">  </span><br><span class="line"><span class="keyword">def</span> <span class="title function_">reduce</span>(<span class="params">f, s, initial</span>):  <span class="comment">#递归</span></span><br><span class="line">	<span class="string">&quot;&quot;&quot;Combine elements of s using f starting with initial  </span></span><br><span class="line"><span class="string">  </span></span><br><span class="line"><span class="string">    &gt;&gt;&gt; reduce(mul, [2, 4, 8], 1)    </span></span><br><span class="line"><span class="string">    64    </span></span><br><span class="line"><span class="string">    &gt;&gt;&gt; reduce(add, [1, 2, 3, 4], 0)</span></span><br><span class="line"><span class="string">	10    </span></span><br><span class="line"><span class="string">	&quot;&quot;&quot;</span> </span><br><span class="line">	<span class="keyword">if</span> <span class="keyword">not</span> s:  </span><br><span class="line">        <span class="keyword">return</span> initial  </span><br><span class="line">    <span class="keyword">else</span>:  </span><br><span class="line">        first, rest = s[<span class="number">0</span>], s[<span class="number">1</span>:]  </span><br><span class="line">        <span class="keyword">return</span> reduce(f, rest, f(initial, first))</span><br><span class="line"></span><br><span class="line"><span class="meta">&gt;&gt;&gt; </span>divide_all(<span class="number">1024</span>, [<span class="number">2</span>,<span class="number">4</span>,<span class="number">8</span>,<span class="number">0</span>])</span><br><span class="line">inf</span><br><span class="line"><span class="meta">&gt;&gt;&gt; </span>divide_all(<span class="number">1024</span>, [<span class="number">2</span>,<span class="number">4</span>,<span class="number">8</span>])</span><br><span class="line"><span class="number">16.0</span></span><br></pre></td></tr></table></figure>
<h1 id="Lecture-10-Trees"><a href="#Lecture-10-Trees" class="headerlink" title="Lecture 10: Trees"></a>Lecture 10: Trees</h1><h2 id="Box-and-Pointer-Notation"><a href="#Box-and-Pointer-Notation" class="headerlink" title="Box-and-Pointer Notation"></a><em>Box-and-Pointer Notation</em></h2><ul>
<li>讲了一种指针表示列表元素的方法，有个闭包属性没咋听懂<br><img src="/2023/11/08/CS61A%E5%AD%A6%E4%B9%A0%E7%AC%94%E8%AE%B0/Pasted%20image%2020230809134011.png"></li>
</ul>
<h2 id="Slicing"><a href="#Slicing" class="headerlink" title="Slicing"></a><em>Slicing</em></h2><ul>
<li>一种对已有列表进行“切片”的操作<br>具体操作请看上面的[[#<em>Examples Lists(List Functions)</em>]]</li>
</ul>
<h2 id="Processing-Containing-Values"><a href="#Processing-Containing-Values" class="headerlink" title="Processing Containing Values"></a><em>Processing Containing Values</em></h2><ul>
<li>一些遍历列表和目录的内置函数(稍后制表)<br><img src="/2023/11/08/CS61A%E5%AD%A6%E4%B9%A0%E7%AC%94%E8%AE%B0/Pasted%20image%2020230809140009.png"></li>
</ul>
<table>
<thead>
<tr>
<th>函数名</th>
<th>函数用途</th>
<th>示例</th>
</tr>
</thead>
<tbody><tr>
<td><strong>sum</strong>函数</td>
<td><code>sum(iterable[, start]) -&gt; value</code><br>将所给的可迭代变量（如列表）中的数字与<code>start</code>初始值相加（没有默认为0）</td>
<td><code>&gt;&gt;&gt; sum([2, 3, 4])</code> <br> <code>9</code><br> <code>&gt;&gt;&gt; sum([2, 3, 4], 5)</code><br> <code>14</code> <br> <code>&gt;&gt;&gt; sum([[2, 3], [4]], [])</code> <br> <code>[2, 3, 4]</code></td>
</tr>
<tr>
<td><strong>max</strong>函数</td>
<td><code>max(iterable[, key = func]) -&gt; value</code><br><code>max(a, b, c, ...[, key = func]) -&gt; value</code><br>输出所给的可迭代变量（如列表）中最大的数字，当给出<code>key function</code>时，调用这个函数来计算最大值</td>
<td><code>&gt;&gt;&gt; max(range(5))</code><br> <code>4</code><br> <code>&gt;&gt;&gt; max(0, 1, 2, 3, 4)</code><br><code>4</code><br><code>&gt;&gt;&gt; max(range(10), lambda x: 7 - (x-2) * (x-4))</code><br><code>3</code></td>
</tr>
<tr>
<td><strong>all</strong>函数</td>
<td><code>all(iterable) -&gt; bool</code><br>当所提供的可迭代对象（如列表）中所有元素都为<code>True</code>值或列表为空时返回<code>True</code></td>
<td><code>&gt;&gt;&gt; [x &lt; 5 for x in range(5)]</code><br> <code>[True, True, True, True, True]</code><br> <code>&gt;&gt;&gt; all([x &lt; 5 for x in range(5)])</code><br><code>True</code><br><code>&gt;&gt;&gt; all(range(5))</code><br><code>False</code></td>
</tr>
</tbody></table>
<h2 id="Trees"><a href="#Trees" class="headerlink" title="Trees"></a><em>Trees</em></h2><p>本质上来说，<code>Tree</code>实际上是一种列表嵌套的表示，即将列表作为其他列表中的元素，称之为数据类型的闭包属性(<code>closure property</code>)<br><img src="/2023/11/08/CS61A%E5%AD%A6%E4%B9%A0%E7%AC%94%E8%AE%B0/Pasted%20image%2020230809201405.png"></p>
<ul>
<li>首先介绍了Tree的两种理解方式吧~<ol>
<li>第一种是递归描述(recursive description -&gt; wooden trees): 即每一个树结构都有一个根标签(root label)和若干个枝干(branches)，同时每一个枝干都可以视作为一个子树结构，一个没有枝干的树结构便称之为叶(leaf)</li>
<li>第二种则是亲缘描述(relative description -&gt; family trees): 即树结构上的每一个位置都可以视作一个节点(node)，每个节点所对应的标签(label)都可以是任何值，而每一个节点同时也作为其他节点的父节点或者子节点(parent&#x2F;child)</li>
</ol>
</li>
<li>接下来，是如何让python定义出一个树结构，如果仅用概念抽象表示的话，树应该是这样的<figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br></pre></td><td class="code"><pre><span class="line"><span class="meta">&gt;&gt;&gt; </span>tree(<span class="number">3</span>, [tree(<span class="number">1</span>), </span><br><span class="line"><span class="meta">... </span>    tree(<span class="number">2</span>, [tree(<span class="number">1</span>), </span><br><span class="line"><span class="meta">... </span>       tree(<span class="number">1</span>)])])</span><br><span class="line">[<span class="number">3</span>, [<span class="number">1</span>], [<span class="number">2</span>, [<span class="number">1</span>], [<span class="number">1</span>]]]</span><br></pre></td></tr></table></figure></li>
<li>紧接着，我们来实际在python下通过编写函数来实现构建Tree的过程<ol>
<li>首先我们从构造函数<code>Tree</code>， 选择器函数<code>label</code>和 <code>branches</code> 组成。<figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">def</span> <span class="title function_">tree</span>(<span class="params">label, branches = []</span>):  </span><br><span class="line">    <span class="keyword">for</span> branch <span class="keyword">in</span> branches:   <span class="comment">#引入branch遍历branches列表中的元素</span></span><br><span class="line">        <span class="keyword">assert</span> is_tree(branch), <span class="string">&#x27;Branches must be trees&#x27;</span>   <span class="comment">#运用断言函数判断branches中的每一个元素是否也为Tree</span></span><br><span class="line">    <span class="keyword">return</span> [label] + <span class="built_in">list</span>(branches)   <span class="comment">#返回时将label值转化为列表，并重新构建一个列表递归除label以外的branches</span></span><br><span class="line">  </span><br><span class="line"><span class="keyword">def</span> <span class="title function_">label</span>(<span class="params">tree</span>):   <span class="comment">#返回Tree的第一个值，即root label</span></span><br><span class="line">    <span class="keyword">return</span> tree[<span class="number">0</span>]  </span><br><span class="line">  </span><br><span class="line"><span class="keyword">def</span> <span class="title function_">branches</span>(<span class="params">tree</span>):    <span class="comment">#返回Tree除第一个以外的值，即branches</span></span><br><span class="line">    <span class="keyword">return</span> tree[<span class="number">1</span>:]</span><br></pre></td></tr></table></figure></li>
<li>由上方Tree的定义知，只有当树有一个根标签并且所有分支也是树时，树才是结构良好的。<code>is_tree</code> 函数应用于构造函数<code>tree</code>以验证所有分支是否结构良好。<figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">def</span> <span class="title function_">is_tree</span>(<span class="params">tree</span>):  </span><br><span class="line">    <span class="keyword">if</span> <span class="built_in">type</span>(tree) != <span class="built_in">list</span> <span class="keyword">or</span> <span class="built_in">len</span>(tree) &lt; <span class="number">1</span>:   <span class="comment">#验证一个tree是否不是列表或者是否没有root label</span></span><br><span class="line">        <span class="keyword">return</span> <span class="literal">False</span>  </span><br><span class="line">    <span class="keyword">for</span> branch <span class="keyword">in</span> branches(tree):    </span><br><span class="line">        <span class="keyword">if</span> <span class="keyword">not</span> is_tree(branch):    <span class="comment">#借助branch遍历branches的每一个元素（枝干）是否为Tree</span></span><br><span class="line">            <span class="keyword">return</span> <span class="literal">False</span>  </span><br><span class="line">    <span class="keyword">return</span> <span class="literal">True</span></span><br></pre></td></tr></table></figure></li>
<li>同时用<code>is_leaf</code>函数验证Tree是否有分支<figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">def</span> <span class="title function_">is_tree</span>(<span class="params">tree</span>):</span><br><span class="line">	<span class="keyword">return</span> <span class="keyword">not</span> branches(tree)</span><br></pre></td></tr></table></figure></li>
<li>具体运行情况如下：<figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br></pre></td><td class="code"><pre><span class="line"><span class="meta">&gt;&gt;&gt; </span>t = tree(<span class="number">3</span>, [tree(<span class="number">1</span>), tree(<span class="number">2</span>, [tree(<span class="number">1</span>), tree(<span class="number">1</span>)])])</span><br><span class="line"><span class="meta">&gt;&gt;&gt; </span>t</span><br><span class="line">[<span class="number">3</span>, [<span class="number">1</span>], [<span class="number">2</span>, [<span class="number">1</span>], [<span class="number">1</span>]]]</span><br><span class="line"><span class="meta">&gt;&gt;&gt; </span>label(t)</span><br><span class="line"><span class="number">3</span></span><br><span class="line"><span class="meta">&gt;&gt;&gt; </span>branches(t)</span><br><span class="line">[[<span class="number">1</span>], [<span class="number">2</span>, [<span class="number">1</span>], [<span class="number">1</span>]]]</span><br><span class="line"><span class="meta">&gt;&gt;&gt; </span>label(branches(t)[<span class="number">1</span>])</span><br><span class="line"><span class="number">2</span></span><br><span class="line"><span class="meta">&gt;&gt;&gt; </span>is_leaf(t)</span><br><span class="line"><span class="literal">False</span></span><br><span class="line"><span class="meta">&gt;&gt;&gt; </span>is_leaf(branches(t)[<span class="number">0</span>])</span><br><span class="line"><span class="literal">True</span></span><br></pre></td></tr></table></figure></li>
</ol>
</li>
</ul>
<h2 id="Tree-Processing"><a href="#Tree-Processing" class="headerlink" title="Tree Processing"></a><em>Tree Processing</em></h2><h2 id="Example-Printing-Trees"><a href="#Example-Printing-Trees" class="headerlink" title="Example: Printing Trees"></a><em>Example: Printing Trees</em></h2>
    </article>
    <!-- license -->
    
        <div class="license-wrapper">
            <p>原文作者：<a href="https://binisalegend.github.io">Binisalegend</a>
            <p>原文链接：<a href="https://binisalegend.github.io/2023/11/08/CS61A%E5%AD%A6%E4%B9%A0%E7%AC%94%E8%AE%B0/">https://binisalegend.github.io/2023/11/08/CS61A%E5%AD%A6%E4%B9%A0%E7%AC%94%E8%AE%B0/</a>
            <p>发表日期：<a href="https://binisalegend.github.io/2023/11/08/CS61A%E5%AD%A6%E4%B9%A0%E7%AC%94%E8%AE%B0/">November 8th 2023, 10:40:09 am</a>
            <p>更新日期：<a href="https://binisalegend.github.io/2023/11/08/CS61A%E5%AD%A6%E4%B9%A0%E7%AC%94%E8%AE%B0/">November 8th 2023, 11:32:44 am</a>
            <p>版权声明：本文采用<a rel="license noopener" target="_blank" href="http://creativecommons.org/licenses/by-nc/4.0/">知识共享署名-非商业性使用 4.0 国际许可协议</a>进行许可</p>
        </div>
    
    <!-- paginator -->
    <ul class="post-paginator">
        <li class="next">
            
                <div class="nextSlogan">Next Post</div>
                <a href="/2023/11/08/Python%E5%AD%A6%E4%B9%A0%E7%AC%94%E8%AE%B0/" title="Python学习笔记">
                    <div class="nextTitle">Python学习笔记</div>
                </a>
            
        </li>
        <li class="previous">
            
                <div class="prevSlogan">Previous Post</div>
                <a href="/2023/11/08/Missing-Semester%E5%AD%A6%E4%B9%A0%E7%AC%94%E8%AE%B0/" title="Missing-Semester学习笔记">
                    <div class="prevTitle">Missing-Semester学习笔记</div>
                </a>
            
        </li>
    </ul>
    <!-- comment -->
    
        <div class="post-comment">
            <!-- 来必力 City 版安装代码 -->

    <div id="lv-container" data-id="city" data-uid= MTAyMC81OTE3Mi8zNTYzNA==>
        <script type="text/javascript">
            (function (d, s) {
                var j, e = d.getElementsByTagName(s)[0];
                if (typeof LivereTower === 'function') { return; }
                j = d.createElement(s);
                j.src = 'https://cdn-city.livere.com/js/embed.dist.js';
                j.async = true;

                e.parentNode.insertBefore(j, e);
            })(document, 'script');
        </script>
        <noscript>为正常使用来必力评论功能请激活 JavaScript</noscript>
    </div>


            

            

            

            <!-- utteranc评论 -->


            <!-- partial('_partial/comment/changyan') -->
            <!--PC版-->


            
            

            

        </div>
    
    <!-- timeliness note -->
    <!-- idea from: https://hexo.fluid-dev.com/posts/hexo-injector/#%E6%96%87%E7%AB%A0%E6%97%B6%E6%95%88%E6%80%A7%E6%8F%90%E7%A4%BA -->
    
    <!-- Mathjax -->
    
</main>

                <!-- profile -->
                
            </div>
            <footer class="footer footer-unloaded">
    <!-- social  -->
    
        <div class="social">
            
    
        
            
                <a href="mailto:2446479002@qq.com" class="iconfont-archer email" title=email ></a>
            
        
    
        
            
                <a href="https://github.com/binisalegend" class="iconfont-archer github" target="_blank" title=github></a>
            
        
    
        
            
                <span class="iconfont-archer wechat" title=wechat>
                    
                    <img class="profile-qr" src="/assets/WeChat.jpg" />
                </span>
            
        
    
        
            
                <span class="iconfont-archer qq" title=qq>
                    
                    <img class="profile-qr" src="/assets/QQ.jpg" />
                </span>
            
        
    
        
    
        
    
        
    
        
    
        
    
        
    
        
    
        
    
        
    
        
    
        
    
        
    
        
    
        
    
        
    
        
    


        </div>
    
    <!-- powered by Hexo  -->
    <div class="copyright">
        <span id="hexo-power">Powered by <a href="https://hexo.io/" target="_blank">Hexo</a></span><span class="iconfont-archer power">&#xe635;</span><span id="theme-info">theme <a href="https://github.com/fi3ework/hexo-theme-archer" target="_blank">Archer</a></span>
    </div>
    <!-- website approve for Chinese user -->
    
    <!-- 不蒜子  -->
    
        <div class="busuanzi-container">
            
             
                <span id="busuanzi_container_site_pv">PV: <span id="busuanzi_value_site_pv"></span> :)</span>
            
        </div>
    	
</footer>

        </div>
        <!-- toc -->
        
            <div class="toc-wrapper toc-wrapper-loding" style=







    top:50vh;

>
                <div class="toc-catalog">
                    <span class="iconfont-archer catalog-icon">&#xe613;</span><span>CATALOG</span>
                </div>
                <ol class="toc"><li class="toc-item toc-level-1"><a class="toc-link" href="#Lecture-3-Control%EF%BC%88%E5%87%BD%E6%95%B0%E6%8E%A7%E5%88%B6%EF%BC%89"><span class="toc-number">1.</span> <span class="toc-text">Lecture 3 : Control（函数控制）</span></a><ol class="toc-child"><li class="toc-item toc-level-2"><a class="toc-link" href="#HW01-Variables-Functions-Control"><span class="toc-number">1.1.</span> <span class="toc-text">HW01 : Variables &amp; Functions, Control</span></a></li><li class="toc-item toc-level-2"><a class="toc-link" href="#Lab01-Variables-Functions-Control"><span class="toc-number">1.2.</span> <span class="toc-text">Lab01: Variables &amp; Functions, Control</span></a></li></ol></li><li class="toc-item toc-level-1"><a class="toc-link" href="#Lecture-4-Higher-Order-Functions%EF%BC%88%E9%AB%98%E9%98%B6%E5%87%BD%E6%95%B0%EF%BC%89"><span class="toc-number">2.</span> <span class="toc-text">Lecture 4:Higher-Order Functions（高阶函数）</span></a><ol class="toc-child"><li class="toc-item toc-level-2"><a class="toc-link" href="#function-example-sound"><span class="toc-number">2.1.</span> <span class="toc-text">function example: sound</span></a></li><li class="toc-item toc-level-2"><a class="toc-link" href="#Function-Composition"><span class="toc-number">2.2.</span> <span class="toc-text">Function Composition</span></a></li><li class="toc-item toc-level-2"><a class="toc-link" href="#Function-Currying"><span class="toc-number">2.3.</span> <span class="toc-text">Function Currying</span></a></li><li class="toc-item toc-level-2"><a class="toc-link" href="#HW02-Higher-Order-Functions"><span class="toc-number">2.4.</span> <span class="toc-text">HW02 : Higher-Order Functions</span></a></li></ol></li><li class="toc-item toc-level-1"><a class="toc-link" href="#Lecture-5-Environment-Diagrams%EF%BC%88%E7%A8%8B%E5%BA%8F%E7%8E%AF%E5%A2%83%E7%A4%BA%E6%84%8F%E5%9B%BE%EF%BC%89"><span class="toc-number">3.</span> <span class="toc-text">Lecture 5:Environment Diagrams（程序环境示意图）</span></a><ol class="toc-child"><li class="toc-item toc-level-2"><a class="toc-link" href="#Environments-for-Higher-Order-Functions"><span class="toc-number">3.1.</span> <span class="toc-text">Environments for Higher-Order Functions</span></a></li><li class="toc-item toc-level-2"><a class="toc-link" href="#Higher-Order-Function-Example-Repeat"><span class="toc-number">3.2.</span> <span class="toc-text">Higher-Order Function Example:Repeat</span></a></li><li class="toc-item toc-level-2"><a class="toc-link" href="#Environments-for-Nested-Definitions"><span class="toc-number">3.3.</span> <span class="toc-text">Environments for Nested Definitions</span></a></li><li class="toc-item toc-level-2"><a class="toc-link" href="#Local-Names"><span class="toc-number">3.4.</span> <span class="toc-text">Local Names</span></a></li><li class="toc-item toc-level-2"><a class="toc-link" href="#Lambda-Expressions"><span class="toc-number">3.5.</span> <span class="toc-text">Lambda Expressions</span></a><ol class="toc-child"><li class="toc-item toc-level-3"><a class="toc-link" href="#1-lambda%E8%A1%A8%E8%BE%BE%E5%BC%8F%E7%9B%B8%E5%85%B3"><span class="toc-number">3.5.1.</span> <span class="toc-text">1. lambda表达式相关</span></a></li><li class="toc-item toc-level-3"><a class="toc-link" href="#2-lambda%E4%B8%8Edef%E5%AE%9A%E4%B9%89%E5%87%BD%E6%95%B0%E7%9A%84%E5%8C%BA%E5%88%AB"><span class="toc-number">3.5.2.</span> <span class="toc-text">2. lambda与def定义函数的区别</span></a></li></ol></li><li class="toc-item toc-level-2"><a class="toc-link" href="#Self-Reference"><span class="toc-number">3.6.</span> <span class="toc-text">Self-Reference</span></a></li><li class="toc-item toc-level-2"><a class="toc-link" href="#Lab02-Higher-Order-Functions-Lambda-Expressions-Self-Reference"><span class="toc-number">3.7.</span> <span class="toc-text">Lab02: Higher-Order Functions, Lambda Expressions, Self Reference</span></a><ol class="toc-child"><li class="toc-item toc-level-3"><a class="toc-link" href="#Q1-WWPD-Lambda-the-Free"><span class="toc-number">3.7.1.</span> <span class="toc-text">Q1: WWPD Lambda the Free</span></a></li><li class="toc-item toc-level-3"><a class="toc-link" href="#Q3-Lambdas-and-Currying"><span class="toc-number">3.7.2.</span> <span class="toc-text">Q3: Lambdas and Currying</span></a></li><li class="toc-item toc-level-3"><a class="toc-link" href="#Q4-Count-van-Count"><span class="toc-number">3.7.3.</span> <span class="toc-text">Q4: Count van Count</span></a></li><li class="toc-item toc-level-3"><a class="toc-link" href="#Q5-Both-Paths"><span class="toc-number">3.7.4.</span> <span class="toc-text">Q5: Both Paths</span></a></li></ol></li><li class="toc-item toc-level-2"><a class="toc-link" href="#Data-Representations"><span class="toc-number">3.8.</span> <span class="toc-text">Data Representations</span></a></li><li class="toc-item toc-level-2"><a class="toc-link" href="#61A-Fall-Lecture12-Video-6-Dictionary"><span class="toc-number">3.9.</span> <span class="toc-text">61A Fall Lecture12 Video 6(Dictionary)</span></a></li><li class="toc-item toc-level-2"><a class="toc-link" href="#Examples-Lists-List-Functions"><span class="toc-number">3.10.</span> <span class="toc-text">Examples: Lists(List Functions)</span></a></li><li class="toc-item toc-level-2"><a class="toc-link" href="#Lab-4-Python-Lists-Data-Abstraction"><span class="toc-number">3.11.</span> <span class="toc-text">Lab 4: Python Lists, Data Abstraction</span></a><ol class="toc-child"><li class="toc-item toc-level-3"><a class="toc-link" href="#Q2-Reverse-iteratively"><span class="toc-number">3.11.1.</span> <span class="toc-text">Q2: Reverse (iteratively)</span></a></li><li class="toc-item toc-level-3"><a class="toc-link" href="#Q3-Reverse-recursively"><span class="toc-number">3.11.2.</span> <span class="toc-text">Q3: Reverse (recursively)</span></a></li><li class="toc-item toc-level-3"><a class="toc-link" href="#Q5-Closer-city"><span class="toc-number">3.11.3.</span> <span class="toc-text">Q5: Closer city</span></a></li><li class="toc-item toc-level-3"><a class="toc-link" href="#Q7-Add-Characters"><span class="toc-number">3.11.4.</span> <span class="toc-text">Q7: Add Characters</span></a></li></ol></li></ol></li><li class="toc-item toc-level-1"><a class="toc-link" href="#Lecture-9-Functional-Decomposition-Debugging%EF%BC%88%E5%8A%9F%E8%83%BD%E5%88%86%E8%A7%A3%E4%B8%8E%E8%B0%83%E8%AF%95%EF%BC%89"><span class="toc-number">4.</span> <span class="toc-text">Lecture 9: Functional Decomposition &amp; Debugging（功能分解与调试）</span></a><ol class="toc-child"><li class="toc-item toc-level-2"><a class="toc-link" href="#Assertions"><span class="toc-number">4.1.</span> <span class="toc-text">Assertions</span></a></li><li class="toc-item toc-level-2"><a class="toc-link" href="#Testing"><span class="toc-number">4.2.</span> <span class="toc-text">Testing</span></a></li><li class="toc-item toc-level-2"><a class="toc-link" href="#Print-Debugging"><span class="toc-number">4.3.</span> <span class="toc-text">Print Debugging</span></a></li><li class="toc-item toc-level-2"><a class="toc-link" href="#Interative-Debugging"><span class="toc-number">4.4.</span> <span class="toc-text">Interative Debugging</span></a></li><li class="toc-item toc-level-2"><a class="toc-link" href="#Error-Types"><span class="toc-number">4.5.</span> <span class="toc-text">Error Types</span></a></li><li class="toc-item toc-level-2"><a class="toc-link" href="#Tracebacks"><span class="toc-number">4.6.</span> <span class="toc-text">Tracebacks</span></a></li><li class="toc-item toc-level-2"><a class="toc-link" href="#Exceptions"><span class="toc-number">4.7.</span> <span class="toc-text">Exceptions</span></a></li><li class="toc-item toc-level-2"><a class="toc-link" href="#Rasing-Exceptions-%E5%BC%95%E5%8F%91%E5%BC%82%E5%B8%B8"><span class="toc-number">4.8.</span> <span class="toc-text">Rasing Exceptions(引发异常)</span></a></li><li class="toc-item toc-level-2"><a class="toc-link" href="#Try-Statements"><span class="toc-number">4.9.</span> <span class="toc-text">Try Statements</span></a></li><li class="toc-item toc-level-2"><a class="toc-link" href="#Example-Reduce"><span class="toc-number">4.10.</span> <span class="toc-text">Example: Reduce</span></a></li></ol></li><li class="toc-item toc-level-1"><a class="toc-link" href="#Lecture-10-Trees"><span class="toc-number">5.</span> <span class="toc-text">Lecture 10: Trees</span></a><ol class="toc-child"><li class="toc-item toc-level-2"><a class="toc-link" href="#Box-and-Pointer-Notation"><span class="toc-number">5.1.</span> <span class="toc-text">Box-and-Pointer Notation</span></a></li><li class="toc-item toc-level-2"><a class="toc-link" href="#Slicing"><span class="toc-number">5.2.</span> <span class="toc-text">Slicing</span></a></li><li class="toc-item toc-level-2"><a class="toc-link" href="#Processing-Containing-Values"><span class="toc-number">5.3.</span> <span class="toc-text">Processing Containing Values</span></a></li><li class="toc-item toc-level-2"><a class="toc-link" href="#Trees"><span class="toc-number">5.4.</span> <span class="toc-text">Trees</span></a></li><li class="toc-item toc-level-2"><a class="toc-link" href="#Tree-Processing"><span class="toc-number">5.5.</span> <span class="toc-text">Tree Processing</span></a></li><li class="toc-item toc-level-2"><a class="toc-link" href="#Example-Printing-Trees"><span class="toc-number">5.6.</span> <span class="toc-text">Example: Printing Trees</span></a></li></ol></li></ol>
            </div>
        
        <!-- sidebar -->
        <div class="sidebar sidebar-hide">
    <ul class="sidebar-tabs sidebar-tabs-active-0">
        <li class="sidebar-tab-archives"><span class="iconfont-archer">&#xe67d;</span><span class="tab-name">Archive</span></li>
        <li class="sidebar-tab-tags"><span class="iconfont-archer">&#xe61b;</span><span class="tab-name">Tag</span></li>
        <li class="sidebar-tab-categories"><span class="iconfont-archer">&#xe666;</span><span class="tab-name">Cate</span></li>
    </ul>
    <div class="sidebar-content sidebar-content-show-archive">
        <div class="sidebar-panel-archives">
    <!-- 在 ejs 中将 archive 按照时间排序 -->
    
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
    
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
    
    
    
    
    <div class="total-and-search">
        <div class="total-archive">
        Total : 8
        </div>
        <!-- search  -->
        
    </div>
    
    <div class="post-archive">
    
        
            
            
            <div class="archive-year"> 2023 </div>
            <ul class="year-list">
            
        
        <li class="archive-post-item">
            <span class="archive-post-date">11/08</span>
            <a class="archive-post-title" href="/2023/11/08/%E6%95%B0%E6%8D%AE%E7%BB%93%E6%9E%84%E4%B8%8E%E7%AE%97%E6%B3%95/">数据结构与算法</a>
        </li>
    
        
        <li class="archive-post-item">
            <span class="archive-post-date">11/08</span>
            <a class="archive-post-title" href="/2023/11/08/C++%E4%B8%AD%E7%9A%84STL%E5%AE%B9%E5%99%A8/">C++中的STL容器</a>
        </li>
    
        
        <li class="archive-post-item">
            <span class="archive-post-date">11/08</span>
            <a class="archive-post-title" href="/2023/11/08/Python%E5%AD%A6%E4%B9%A0%E7%AC%94%E8%AE%B0/">Python学习笔记</a>
        </li>
    
        
        <li class="archive-post-item">
            <span class="archive-post-date">11/08</span>
            <a class="archive-post-title" href="/2023/11/08/%E5%A4%A7%E4%BA%8C%E4%B8%8A%E5%B0%8F%E5%AD%A6%E6%9C%9F%E7%A8%8B%E8%AE%BE%E8%A7%A3%E9%A2%98%E6%80%9D%E8%B7%AF/">大二上小学期程设解题思路</a>
        </li>
    
        
        <li class="archive-post-item">
            <span class="archive-post-date">11/08</span>
            <a class="archive-post-title" href="/2023/11/08/%E5%BC%BA%E5%8C%96%E5%AD%A6%E4%B9%A0%E7%AC%94%E8%AE%B0/">强化学习笔记</a>
        </li>
    
        
        <li class="archive-post-item">
            <span class="archive-post-date">11/08</span>
            <a class="archive-post-title" href="/2023/11/08/CS61A%E5%AD%A6%E4%B9%A0%E7%AC%94%E8%AE%B0/">CS61A学习笔记</a>
        </li>
    
        
        <li class="archive-post-item">
            <span class="archive-post-date">11/08</span>
            <a class="archive-post-title" href="/2023/11/08/Missing-Semester%E5%AD%A6%E4%B9%A0%E7%AC%94%E8%AE%B0/">Missing-Semester学习笔记</a>
        </li>
    
        
        <li class="archive-post-item">
            <span class="archive-post-date">11/07</span>
            <a class="archive-post-title" href="/2023/11/07/Java%E7%A8%8B%E5%BA%8F%E8%AE%BE%E8%AE%A1%E5%AD%A6%E4%B9%A0%E7%AC%94%E8%AE%B0/">Java程序设计学习笔记</a>
        </li>
    
    </div>
</div>

        <div class="sidebar-panel-tags">
    <div class="sidebar-tags-name">
        
            <span class="sidebar-tag-name" data-tags="Python">
                <span class="iconfont-archer">&#xe606;</span>
                Python
            </span>
        
            <span class="sidebar-tag-name" data-tags="Java语言学习">
                <span class="iconfont-archer">&#xe606;</span>
                Java语言学习
            </span>
        
            <span class="sidebar-tag-name" data-tags="杂技学习">
                <span class="iconfont-archer">&#xe606;</span>
                杂技学习
            </span>
        
            <span class="sidebar-tag-name" data-tags="数据结构">
                <span class="iconfont-archer">&#xe606;</span>
                数据结构
            </span>
        
            <span class="sidebar-tag-name" data-tags="强化学习">
                <span class="iconfont-archer">&#xe606;</span>
                强化学习
            </span>
        
    </div>
    <div class="iconfont-archer sidebar-tags-empty">&#xe678;</div>
    <div class="tag-load-fail" style="display: none; color: #ccc; font-size: 0.6rem;">
        缺失模块，请参考主题文档进行安装配置：https://github.com/fi3ework/hexo-theme-archer#%E5%AE%89%E8%A3%85%E4%B8%BB%E9%A2%98
    </div> 
    <div class="sidebar-tags-list"></div>
</div>

        <div class="sidebar-panel-categories">
    <div class="sidebar-categories-name">
    
    </div>
    <div class="iconfont-archer sidebar-categories-empty">&#xe678;</div>
    <div class="sidebar-categories-list"></div>
</div>

    </div>
</div>

        <!-- site-meta -->
        <script>
    var siteMetaRoot = "/"
    if (siteMetaRoot === "undefined") {
        siteMetaRoot = '/'
    }
    var siteMeta = {
        url: "https://binisalegend.github.io",
        root: siteMetaRoot,
        author: "Binisalegend"
    }
</script>

        <!-- import experimental options here -->
        <!-- Custom Font -->


        <!-- main func -->
        <script src="/scripts/main.js?v=20211217"></script>
        <!-- dark mode -->
        <script src="/scripts/dark.js?v=20211217"></script>
        <!-- fancybox -->
        <script src="https://cdn.jsdelivr.net/npm/@fancyapps/fancybox@3.5.7/dist/jquery.fancybox.min.js" defer></script>
        <!-- algolia -->
        
        <!-- busuanzi -->
        
            <script src="//busuanzi.ibruce.info/busuanzi/2.3/busuanzi.pure.mini.js" async></script>
        
        <!-- CNZZ -->
        
        <!-- async load share.js -->
        
            <script src="/scripts/share.js?v=20211217" async></script>
        
        <!-- mermaid -->
        
    </body>
</html>
